将自定义响应标头添加到IHttpActionResult类(或添加Auth令牌作为响应)

时间:2019-06-20 13:58:22

标签: c# rest authentication asp.net-core-webapi

我一直在尝试为我的Web Api项目进行登录控制。一切工作正常,我还处理了令牌生成以及身份验证功能。我主要担心的是,我无法作为请求的响应提供作为用户的Auth方法生成的令牌。我已经尝试了几种方法,但没有一种起作用。

这些示例是通过浏览stackoverflow收集的,以查看是否有任何解决方案有效,但无济于事。我还可以发布使用的Helper类(例如HttpActionResultExtensions.cs,它将“ AddHeader”方法添加到结果中。)

public class LoginController : ApiController
{
    private UserService _userService = new UserService();

    [HttpPost]
    public IHttpActionResult Authenticate([FromBody]LoginRequest loginData)
    {
        IHttpActionResult response;
        LoginResponse loginResponse = new LoginResponse { };


        if (loginData == null)
        {
            loginResponse.responseMsg.StatusCode = HttpStatusCode.BadRequest;
            response = ResponseMessage(loginResponse.responseMsg);
            return response;
        }

        User user = _userService.Authenticate(loginData.Username, loginData.Password);

        if (user.Token == null)
        {
            loginResponse.responseMsg.StatusCode = HttpStatusCode.Unauthorized;
            response = ResponseMessage(loginResponse.responseMsg);
            return response;
        }

        /*Request.Content.Headers.Add("Authorisation", user.Token);
        Request.Headers.Add("Authorisation", user.Token);
        return Ok(loginResponse);*/

        /*HttpResponseMessage responseMessage = new HttpResponseMessage(HttpStatusCode.OK);
        responseMessage.Content.Headers.Add("Authorisation", user.Token);
        //response.Content.Headers.Add("Access-Control-Expose-Headers", "Filename");
        responseMessage.Content.Headers.Add("Access-Control-Expose-Headers", "Authorisation");
        ResponseMessageResult responsez = new ResponseMessageResult(responseMessage);
        return responsez;*/

        //return Ok(user).AddHeader("Authorisation", user.Token);
        //return new HeaderActionResult(Tuple.Create("Authorization", user.Token));

        var Result = new { Status = "Ok", Message = user };

        var Response = Request.CreateResponse(HttpStatusCode.OK, Result);
        Response.Headers.Add("Authorisation", user.Token);

        return ResponseMessage(Response);
    }

}

0 个答案:

没有答案