Angular 6 .Net Core 2.2 App中的Cors错误 [英] Cors error in Angular 6 .Net core 2.2 App
本文介绍了Angular 6 .Net Core 2.2 App中的Cors错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经开发了.Net Core MVC(角度)应用程序和.net Core Api应用程序
I have developed the .Net Core MVC (angular) app and .net core Api app
在两个应用程序中,我均已在Web应用程序和api中启用了CORS
In both apps I have enabled the CORS in both Web app and api
.Net Core
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
// in Configure
app.UseCors("CorsPolicy");
角度
对于所有获取"和发布",请添加如下标题:
For all Get and Post add the headers like below
get(url: string, options?: any) {
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Accept', 'applcation/ json');
options = { headers: headers };
const _url = this.webapiurl + url;
return this.http.get(_url, options);
}
仍然面临CORS错误
Access to XMLHttpRequest at 'http://etestservice.qa.com:5003/QA/api/test/GetDetails?email=abc@gmail.com' from origin 'http://etestweb.qa.com::5002' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
推荐答案
在startup.cs文件中
In startup.cs file
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// app settings configuration.
services.AddCors(options =>
{
// this defines a CORS policy called "default"
options.AddPolicy("AllowSpecificOrigin", policy =>
{
var corsUrlSection = Configuration.GetSection("AllowedOrigins");
var corsUrls = corsUrlSection.Get<string[]>();
policy.WithOrigins(corsUrls)
.AllowAnyHeader()
.WithExposedHeaders("X-Pagination") // add any customer header if we are planning to send any
.AllowAnyMethod();
});
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment environment, ILoggerFactory loggerFactory)
{
app.UseExceptionMiddleware();
// Use HTTPS Redirection Middleware to redirect HTTP requests to HTTPS.
app.UseHttpsRedirection();
app.UseCors("AllowSpecificOrigin");
app.UseMvc();
}
在API中,
[EnableCors("AllowSpecificOrigin")]
public class Controller
{
// code...
}
必须订购中间件组件.所以检查一下.我已经在这里附上我的项目代码.
The order of the Middleware components is a must. So check it. I have attached here my project code.
这篇关于Angular 6 .Net Core 2.2 App中的Cors错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文