繁体   English   中英

无法从 Web API2 获取 Angular JS 中的响应标头

[英]Not able to get response header in angular JS from Web API2

以下是 Web API2 方法返回的响应:

Response Headers

{
  "cache-control": "no-cache",
  "pragma": "no-cache",
  "content-type": "application/json; charset=utf-8",
  "expires": "-1",
  "server": "Microsoft-IIS/10.0",
  "token": "ac3903cc-7c9b-469a-85ea-677ff9773d43",
  "tokenexpiry": "900",
  "access-control-expose-headers": "Token,TokenExpiry",
  "x-aspnet-version": "4.0.30319",
  "x-sourcefiles": "=?UTF-8?B?QzpcRGV2ZWxvcG1lbnRcV2ViQXBpXFJlc3RXZWJBUElcV2ViQXBpRG9zQWRtaW5cV2ViQXBpRG9zQWRtaW5cYXBpXGF1dGhlbnRpY2F0ZQ==?=",
  "x-powered-by": "ASP.NET",
  "date": "Thu, 01 Dec 2016 10:09:11 GMT",
  "content-length": "12",
  "": ""
}

我试图在我的 AngularJS 代码中获取“令牌”,但我无法获取它。 我得到 Null 或 Undefined:

$http.post('http://localhost:37690//api/authenticate', {Username:username,Password:password})
                .success(function (response,headers) {
                    //callback(response);
                    debugger;
                    if(response==='Authorized')
                    {
                        var hd=headers.common['Token'];
                        console.log(hd);
                    }
                })
            .error(function (err, status) {
                console.log(err);
            });

我在我的 Web API 项目中启用了 CORS。 以下是我在 WebAPIconfig.cs 中编写的内容:

public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            config.EnableCors();

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }

我的 AuthenticateController 类:

using System.Web.Http.Cors;
[EnableCors(origins: "*", headers: "*", methods: "*")]
    public class AuthenticateController : ApiController
    {
[Route("api/authenticate")]
        [HttpPost]
        public HttpResponseMessage Authenticate(UserLogin user)
        {
            int UserID = _userService.Authenticate(user);            
            return GetAuthToken(UserID); ;
        }

        /// <summary>
        /// Returns auth token for the validated user.
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        private HttpResponseMessage GetAuthToken(int userId)
        {
            var token = _tokenService.GenerateToken(userId);
            var response = Request.CreateResponse(HttpStatusCode.OK, "Authorized");
            response.Headers.Add("Token", token.AuthToken);
            response.Headers.Add("TokenExpiry", ConfigurationManager.AppSettings["AuthTokenExpiry"]);
            response.Headers.Add("Access-Control-Expose-Headers", "Token,TokenExpiry");
            return response;
        }    

    }

请帮助我如何在 Angular JS 端的响应中获取标题?

文档显示 headers 是一个 getter 函数

标头 – {function([headerName])} – 标头 getter 函数。

然后你需要把它当作成功回调中的一个

$http.post('http://localhost:37690//api/authenticate', {Username:username,Password:password})
    .success(function (response,headers) {

        //Either get all headers in one call
        headers = headers();

        //Then get the headers like this 
        var hd1=headers['token'];
        var hd2=headers['tokenexpiry'];

        //Or call the header one by one
        var hd1 = headers('token');
        var hd2 = headers('tokenexpiry');

    })
.error(function (err, status) {
    console.log(err);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM