【问题标题】:Cant get the asp.net Web API token using http client无法使用 http 客户端获取 asp.net Web API 令牌
【发布时间】:2013-11-14 10:28:10
【问题描述】:

我正在尝试使用 http 客户端调用 Web API 以获取令牌。我有一个 MVC 应用程序和 Web API 应用程序。下面是我拥有的 MVC 控制器操作。

[HttpPost]
public ActionResult Login()
{
    LoginModel m = new LoginModel();
    m.grant_type = "password";
    m.username = "xxx";
    m.password = "xxx1234";
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri("http://localhost:51540/"); 
    var response = client.PostAsJsonAsync("Token", m).Result;
    response.EnsureSuccessStatusCode();
    return View();
}

但是当我发出请求时,API 会以 BAD 请求响应。我尝试将内容类型添加为“application/json”,并使用 fiddler 确认请求是 json 类型。

我能够使用 Web API 注册用户,所以在 WebAPI 方面对我来说一切都很好,我正在使用 VS2013 使用个人帐户创建的默认项目,并且在 API 方面没有修改任何东西。

我正在关注本教程 http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api 并尝试使用 HTTP 客户端而不是提琴手。

如果有人帮助我,我将不胜感激

【问题讨论】:

    标签: c# asp.net-web-api2 owin claims-based-identity


    【解决方案1】:

    TokenEndpointRequest 似乎还不支持 JSON,但你可以使用查询字符串

    var response = client.PostAsync("Token", new StringContent("grant_type=password&username=xxx&password=xxx1234", Encoding.UTF8)).Result;
    

    【讨论】:

      【解决方案2】:

      这是我上面答案和评论中的代码

      using (var client = new HttpClient{ BaseAddress = new Uri(BaseAddress) })
      {
          var token = client.PostAsync("Token", 
              new FormUrlEncodedContent(new []
              {
                  new KeyValuePair<string,string>("grant_type","password"),
                  new KeyValuePair<string,string>("username",user.UserName),
                  new KeyValuePair<string,string>("password","P@ssW@rd")
              })).Result.Content.ReadAsAsync<AuthenticationToken>().Result;
      
          client.DefaultRequestHeaders.Authorization = 
                 new AuthenticationHeaderValue(token.token_type, token.access_token);
      
          // actual requests from your api follow here . . .
      }
      

      为美化目的创建了一个 AuthenticationToken 类:

      public class AuthenticationToken
      {
          public string access_token { get; set; }
          public string token_type { get; set; }
          public int expires_in { get; set; }
      }
      

      【讨论】:

        猜你喜欢
        • 2015-06-02
        • 1970-01-01
        • 1970-01-01
        • 2014-11-06
        • 1970-01-01
        • 2011-10-29
        • 1970-01-01
        • 1970-01-01
        • 2017-10-02
        相关资源
        最近更新 更多