无法使用http客户端获取asp.net Web API令牌

问题描述 投票:4回答:2

我正在尝试使用http客户端调用Web API来获取令牌。我有一个MVC应用程序和Web API app.below是我拥有的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 Client而不是fiddler。

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

c# asp.net-web-api2 owin claims-based-identity
2个回答
17
投票

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

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

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","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; }
}
© www.soinside.com 2019 - 2024. All rights reserved.