has*_*eeb 1 c# asp.net-mvc authorization asp.net-web-api
我正在按照本教程讲解如何授权和从Web-api服务器获取承载令牌。通过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"];
}
Run Code Online (Sandbox Code Playgroud)
有人可以帮助我确定我在做什么错吗?还是我应该使用其他方法来获取身份验证令牌?
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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9576 次 |
| 最近记录: |