2013-11-14 112 views
4

我想使用http客户端来调用Web API来获取令牌。我有一个MVC应用程序和Web API app.below是MVC控制器操作我有。无法获取使用http客户端的asp.net Web API令牌

[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客户端而不是fiddler。

我会很感激,如果有人可以帮助我

回答

17

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

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

谢谢,我使用fomrurlencoded content – varun

1

以下是上述

答案&评论我的代码
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","[email protected]@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; } 
} 
相关问题