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?