【发布时间】:2019-01-12 10:15:46
【问题描述】:
不断收到 No 'Access-Control-Allow-Origin' header is present 使用 asp.net core 2.1 的角度 6 中的错误。
我知道这是 cors 错误。我已经在服务器端添加了策略,但仍然是同样的问题。
startup.cs
services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials().WithOrigins("http://localhost:4200");
}));
app.UseCors("CorsPolicy");
app.UseMvc();
控制器代码
[HttpPost, AllowAnonymous]
public GenericResponseObject<JwtTokenViewModel> UserAuthentication([FromBody] UserViewModel user)
{
GenericResponseObject<JwtTokenViewModel> genericResponseObject = new GenericResponseObject<JwtTokenViewModel>();
genericResponseObject.IsSuccess = false;
genericResponseObject.Message = ConstaintStingValue.TagConnectionFailed;
if (ModelState.IsValid)
{
try
{
UserViewModel userViewModel = _adminUOW.AdminAuthentication(user);
if (userViewModel != null)
{
string token = new CommonController(tokenOptions).GetToken(userViewModel, DateTime.UtcNow.AddDays(2));
genericResponseObject.Data = new JwtTokenViewModel
{
UserName = userViewModel.UserName,
UserId = userViewModel.UserId,
authenticated = true,
entityId = 1,
tokenExpires = DateTime.UtcNow.AddHours(2),
token = token,
SelectedRole = userViewModel.SelectedRole
};
}
else
{
genericResponseObject.SuccessMessage = ConstaintStingValue.Tag_No_Profile_key;
}
genericResponseObject.IsSuccess = true;
genericResponseObject.Message = ConstaintStingValue.TagConnectionSuccess;
}
catch (Exception exception)
{
genericResponseObject.IsSuccess = true;
genericResponseObject.SuccessMessage = exception.Message;
genericResponseObject.ErrorCode = exception.HResult;
genericResponseObject.ExceptionErrorMessage = exception.StackTrace;
WriteExceptionToFile.WriteExceptionToFileInLogger(_hostingEnvironment, exception);
}
}
return genericResponseObject;
}
打字稿代码
login(modelValue: UserViewModel, isValid: boolean) {
if (isValid) { this.genericHttpClientService.GenericHttpPostAndResponse<GenericResponseObject<JwtTokenViewModel>, UserViewModel>(this._userViewModel, this.commonConstantValue.adminLoginUrl).subscribe(item => {
if (item.data!= null && item.data.authenticated) {
this.router.navigate(['admin-portal']);
}else{
this.genericViewModel.successMessage = item.successMessage;
}
this.progressBarDisplay = false;
},
err => {
console.log(err);
this.progressBarDisplay = false;
});
}
public GenericHttpPostAndResponse<T,TE>(postViewModel: TE, destinationUrl: string): Observable<T> {
const headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');
return this.httpClientModule.post<T>(environment.baseUrl + destinationUrl, postViewModel, { headers });
}
How to enable CORS in ASP.net Core WebAPI
https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.1
【问题讨论】:
-
你能分享你的api代码吗?
-
添加控制器代码.....
-
你为 5001 端口设置 HTTPS 了吗?
-
对于令牌请求,不需要来自正文。此外,您应该提供内容类型:application/x-www-form-urlencoded
-
注意
AllowAnyOrigin()会清空origins列表,然后将*添加到origins,后面的WithOrigins会添加"http://localhost:4200"到origins列表。所以,WithOrigins在AllowAnyOrigin之后是不必要的,可能是你的问题的原因。
标签: c# asp.net angular typescript asp.net-core