以下是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结尾处获得标题?
答案 0 :(得分:0)
documentation显示标头是一个getter函数
headers - {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);
});