如何访问Angular JS应用程序中的Asp.Net Web Api响应中添加的自定义Token标头?

时间:2016-03-08 06:52:36

标签: asp.net angularjs asp.net-web-api

    //My login method is as follows, which takes credentials and validates them against a db table entries
    [HttpPost]
    [Route("api/login")]
    public IHttpActionResult Authenticate([FromBody]LoginModel credentials)
    {
        IHttpActionResult result;
        HttpResponseMessage response;
        TokenModel tokenInfo;
        var userId = (from n in _data.Users
                      where n.id == credentials.id && n.Password == credentials.Password
                      select n.id).FirstOrDefault().ToString();

        if (!string.IsNullOrEmpty(userId))
        {
            //Following mehtod generates a token and stores it in db for further usage
            tokenInfo = tokenFunctions.GenerateToken(userId);
            if (tokenInfo != null)
            {
                //Creating response message with custom headers info
                response = Request.CreateResponse(HttpStatusCode.OK, userId);
                response.Headers.Add("Token", tokenInfo.AuthToken);
                response.Headers.Add("TokenExpiry", ConfigurationManager.AppSettings["AuthTokenExpiry"]);
                response.Headers.Add("Access-Control-Expose-Headers", "Token");
            }
            else
            {
                response = Request.CreateResponse(HttpStatusCode.Unauthorized);
            }

            result = ResponseMessage(response);
            return result;
        }

        return Unauthorized();
    }

当我通过fiddler访问上述方法时,我能够在“Miscellaneous”部分下看到Token和TokenExpiry标题。但是当我尝试从角度JS应用程序访问此方法时,我无法在$ http.post()回调方法的headers参数中看到Token / TokenExpiry标头。 有谁可以帮我解决这个问题?你的回复对我很有帮助。

0 个答案:

没有答案