我正在编写一个Windows Phone 8应用程序,它使用API来提取应用程序所需的一些数据,并使用api,需要用户名和密码。我已经提供了这个用户名和密码,它似乎工作,但我想知道在应用程序中使用它的正确方法是什么?
我可以简单地添加以下内容:
string userName = "username";
string passWord = "password";
然后在需要时将它们传递到WebRequest
?或者我是否应该在应用程序中存储此信息?
为了清楚起见,用户不需要自己的用户名或密码,这个通用的用户名或密码应该可以使用。
答案 0 :(得分:3)
您可以加密隔离存储中的数据。 Here是一个教程
如果链接发生故障,这里是应用程序的代码,可以写入和读取密码。
using System.IO;
using System.IO.IsolatedStorage;
using System.Text;
using System.Security.Cryptography;
private string FilePath = "pinfile";
private void BtnStore_Click(object sender, RoutedEventArgs e)
{
// Convert the PIN to a byte[].
byte[] PinByte = Encoding.UTF8.GetBytes(TBPin.Text);
// Encrypt the PIN by using the Protect() method.
byte[] ProtectedPinByte = ProtectedData.Protect(PinByte, null);
// Store the encrypted PIN in isolated storage.
this.WritePinToFile(ProtectedPinByte);
TBPin.Text = "";
}
private void WritePinToFile(byte[] pinData)
{
// Create a file in the application's isolated storage.
IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream writestream = new IsolatedStorageFileStream(FilePath, System.IO.FileMode.Create, System.IO.FileAccess.Write, file);
// Write pinData to the file.
Stream writer = new StreamWriter(writestream).BaseStream;
writer.Write(pinData, 0, pinData.Length);
writer.Close();
writestream.Close();
}
private void BtnRetrieve_Click(object sender, RoutedEventArgs e)
{
// Retrieve the PIN from isolated storage.
byte[] ProtectedPinByte = this.ReadPinFromFile();
// Decrypt the PIN by using the Unprotect method.
byte[] PinByte = ProtectedData.Unprotect(ProtectedPinByte, null);
// Convert the PIN from byte to string and display it in the text box.
TBPin.Text = Encoding.UTF8.GetString(PinByte, 0, PinByte.Length);
}
private byte[] ReadPinFromFile()
{
// Access the file in the application's isolated storage.
IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream readstream = new IsolatedStorageFileStream(FilePath, System.IO.FileMode.Open, FileAccess.Read, file);
// Read the PIN from the file.
Stream reader = new StreamReader(readstream).BaseStream;
byte[] pinArray = new byte[reader.Length];
reader.Read(pinArray, 0, pinArray.Length);
reader.Close();
readstream.Close();
return pinArray;
}
答案 1 :(得分:2)
我不知道有任何问题需要您为任何不同形式的代码设置样式
WebRequest request = WebRequest.Create("http://SomeProtectedUrl.com");
request.Credentials = new System.Net.NetworkCredential("username", "password");
将您的用户名和密码保存在一个位置,以便您可以轻松更改
public static string uname = "yourUsername";
public static string passwd= "yourPassword";
request.Credentials = new System.Net.NetworkCredential(uname, passwd);