【发布时间】:2019-06-01 19:45:17
【问题描述】:
我正在使用 Angular 7 来制作简单的身份验证应用程序。我已经通过 asp.net wep api 2 在标头中设置了令牌。 这是这个的代码
[Route("api/AuthEmployees")]
[AcceptVerbs("POST")]
public IHttpActionResult Login(string userName, string password)
{
try
{
Employee employee = Saloon.Employees.FirstOrDefault(x => x.UserName.Equals(userName) && x.Password.Equals(password));
if (employee != null && !(bool) employee.isAuthenticated)
{
employee.isAuthenticated = true;
employee.authenticationkey = Guid.NewGuid().ToString().Replace("-", "");
HttpContext.Current.Response.Headers.Add("X-Token", employee.authenticationkey);
Saloon.SaveChanges();
employee.Password = "";
return Json(employee.authenticationkey);
}
else if(employee != null && (bool) employee.isAuthenticated)
{
employee.authenticationkey = RefreshToken(employee.authenticationkey);
HttpContext.Current.Response.Headers.Add("X-Token", employee.authenticationkey);
return Json(employee.authenticationkey);
}
else
{
return InternalServerError();
}
}
catch (Exception)
{
throw;
}
}
在我的 Angular 应用程序中,我尝试使用“Response”类来获取标头值,但它每次都返回 null。 这是用于身份验证的服务类
public authEmployee(userName:string,password:string) :Observable<any>
{
console.log('Auth employee service called');
return this.http.post<any>(this.API_ADDRESS + '/api/AuthEmployees',
{httpOptions:this.httpOptions} ,
{
params:
{
username: userName, password: password
}
}
);
}
httpOptions 在哪里
httpOptions ={ headers: new HttpHeaders({ 'Content-Type': 'application/json'})};
这是我的组件。
getAuth():void
{
this.authService.authEmployee(this.username,this.password).subscribe(
(x:Response) =>
{
console.log('Success Called')
console.log(x.headers.get('X-Token')) //Always returns null
this.callRedirect();
},
(error)=>
{
console.log('Error Called')
console.log(error)
this.callRedirect();
},
() => {
});
}
我也尝试在我的 httpOptions 中使用观察:“响应”,但它也不起作用。请帮我解决这个问题。谢谢
【问题讨论】:
标签: angular