c# - 我如何在 .Net 控制台应用程序中获取不记名 token ?

标签 c# asp.net-mvc asp.net-web-api authorization

我正在关注 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/

相关文章:

javascript - 在 C# 中将变量传递给 imagebutton onclientclick 中的 javascript

c# - 将 Between 和其他函数作为 LINQ 表达式实现

c# - 调用 EventHandler 泛型,TargetParameterCountException

c# - 如何设置 NLOG 使用多个数据库

ASP.NET Web Api (REST) : Authentication using the users credentials or a token? 保留 "Register new user"资源密码吗?

asp.net-mvc-4 - ASP.NET Web API 的自定义 MVC AuthorizeAttribute

c# - 将 IObservable<Task<T>> 解包为 IObservable<T> 并保留顺序

asp.net-mvc - ASP.NET MVC中的ModelFactory解决 'RenderPartial'问题

c# - 在登录后保护整个网站,即 "Authorize"所有 Controller 中的所有操作

c# - System.Web.Http.HttpPut 与 System.Web.Mvc.HttpPut 之间有什么区别