我正在关注 this关于如何从 web-api 服务器授权和获取不记名 token 的教程。通过 fiddler 执行的任务非常简单,但是,当我尝试从控制台应用程序执行相同操作时,请求失败并显示 400 Bad Request Error
。这是向服务器发出请求的代码:
var request = WebRequest.Create("http://localhost:12698/token") as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = new CookieContainer();
var authCredentials = "userName=" + user + "&password=" + password;
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(authCredentials);
request.ContentLength = bytes.Length;
using (var requestStream = request.GetRequestStream()){
requestStream.Write(bytes, 0, bytes.Length);
}
using (var response = request.GetResponse() as HttpWebResponse){
authCookie = response.Cookies["access_token"];
}
有人可以帮助我确定我在这里做错了什么吗?还是我应该使用其他方法来获取身份验证 token ?
最佳答案
FormUrlEncodedContent 在 System.Net.Http 中
static string GetToken(string userName, string password)
{
var pairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>( "grant_type", "password" ),
new KeyValuePair<string, string>( "userName", userName ),
new KeyValuePair<string, string> ( "password", password )
};
var content = new FormUrlEncodedContent(pairs);
using (var client = new HttpClient())
{
var response =
client.PostAsync("https://localhost:12698/Token", content).Result;
return response.Content.ReadAsStringAsync().Result;
}
}
关于c# - 我如何在 .Net 控制台应用程序中获取不记名 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24842321/