0

Following is the response returned by Web API2 method:

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",
  "": ""
}

I am trying to get the "token" in my AngularJS code but I am not able to get it. I am getting Null or 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);
            });

I have enabled CORS in my Web API project. Following is what I have written in 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 }
            );
        }

My AuthenticateController class:

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;
        }    

    }

Please help as to how can I get header in my response in Angular JS end?

1 Answer 1

0

The documentation shows that headers is a getter function

headers – {function([headerName])} – Header getter function.

You then need to treat it like one in the success callback

$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);
});
4
  • I don't get it, what are you suggesting to change in my code so that I get back the header? Commented Dec 1, 2016 at 13:51
  • Replace your success callback with the one I posted. The headers is a function. In your example you do like this "headers.common.." When you should call the function headers() Commented Dec 1, 2016 at 13:56
  • This is not working, I am getting undefined when I use headers['token']. Can you please help? Commented Dec 5, 2016 at 8:47
  • Ok, how about var hd1 = headers('token');? Commented Dec 5, 2016 at 8:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.