【问题标题】:Not able to get response header in angular JS from Web API2无法从 Web API2 获取角度 JS 中的响应标头
【发布时间】:2020-01-08 15:15:19
【问题描述】:

以下是 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 端的响应中获取标题?

【问题讨论】:

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


    【解决方案1】:

    documentation 表明 headers 是一个 getter 函数

    headers – {function([headerName])} – Header 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);
    });
    

    【讨论】:

    • 我不明白,你有什么建议改变我的代码以便我找回标题?
    • 将您的成功回调替换为我发布的回调。标题是一个函数。在您的示例中,您确实喜欢这个“headers.common ..”当您应该调用函数 headers()
    • 这不起作用,当我使用 headers['token'] 时,我变得不确定。你能帮忙吗?
    • 好的,var hd1 = headers('token'); 怎么样?
    猜你喜欢
    • 2021-10-21
    • 1970-01-01
    • 2018-04-23
    • 2019-12-25
    • 1970-01-01
    • 2014-02-26
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    相关资源
    最近更新 更多