如何向Response.Header添加授权?

时间:2017-09-05 19:16:47

标签: asp.net json reactjs asp.net-authorization

我有以下控制器功能:

    [HttpGet("[action]")]
    public async Task<HttpResponseMessage> Login(string username, string password)
    {
        var user = await _userManager.FindByNameAsync(username);
        var res = await _signInManager.CheckPasswordSignInAsync(user, password, false);

        if (res.Succeeded)
        {
            var msg = new HttpResponseMessage(HttpStatusCode.OK);
            msg.Headers.Add("Authorization", JwtManager.GenerateToken(username));
            return msg;
        }
        else
            return new HttpResponseMessage(HttpStatusCode.BadRequest);// Request.CreateResponse(HttpStatusCode.BadRequest, new object());
    }

在React的reducer中我有这个:

let fetchTask = fetch('http://localhost:25565/api/mediaengine/login?username=' + userName + '&password=' + password)

            .then(response => {
                var k = response.headers.get("Authorization");
                var l = 0;
            })
            .catch(e => {
            });
        addTask(fetchTask);

由于某种原因,response.headers.get(“授权”)将返回null ..

1 个答案:

答案 0 :(得分:1)

您应该从api返回响应。这可以使用HttpResponseMessage类

来完成
[HttpGet("[action]")]
public async Task<HttpResponseMessage> Login(string username, string password)
{
    var user = await _userManager.FindByNameAsync(username);
    var res = await _signInManager.CheckPasswordSignInAsync(user, password, false);

    if(res.Succeeded)
    {
        var response = Request.CreateResponse(HttpStatusCode.OK, new object());
        response.Headers.Add("Authorization", JwtManager.GenerateToken(username));
        return response;
    }else
        return Request.CreateResponse(HttpStatusCode.BadRequest, new object());
}