CORS错误调用ASP.. NET Core 5 Web Application for teleerik Report



按照这里的Telerik演练创建Telerik Report主机。

在.NET CORE 5项目中,我启用CORS如下:

在Startup.cs

public void ConfigureServices(IServiceCollection services)
{
services.AddControllers().AddNewtonsoftJson();
services.AddRazorPages();
// Configure dependencies for ReportsController.
services.TryAddSingleton<IReportServiceConfiguration>(sp =>
new ReportServiceConfiguration
{
//ReportingEngineConfiguration = ConfigurationHelper.ResolveConfiguration(sp.GetService<IWebHostEnvironment>()),
ReportingEngineConfiguration = sp.GetService<IConfiguration>(),
HostAppId = "Net5RestServiceWithCors",
Storage = new FileStorage(),
ReportSourceResolver = new UriReportSourceResolver(
System.IO.Path.Combine(sp.GetService<IWebHostEnvironment>().ContentRootPath, "Reports"))
});
services.AddCors(corsOption => corsOption.AddPolicy(
"ReportingRestPolicy",
corsBuilder =>
{
corsBuilder.WithOrigins("*")
.AllowAnyMethod()
.AllowAnyHeader();
//corsBuilder.AllowAnyOrigin()
//  .AllowAnyMethod()
//  .AllowAnyHeader();
}
));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors("ReportingRestPolicy");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapRazorPages();
});

}

launchSettings.cs如下:

"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:65271",
"sslPort": 44398
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"MyReportServer": {
"commandName": "Project",
"dotnetRunMessages": "true",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

为了测试,我运行项目并将URL更改为https://localhost:44398/api/reports/version,然后我收到正确的响应"16.1.22.511"

然后我打开一个新的web浏览器,导航到https://localhost:44398/api/reports/version,并得到相同的有效响应。

在我的前端项目中,我将报告url设置为:

var reporturi = "https://localhost:44398/api/reports"

当报表查看器开始报表检索过程时,它首先调用报表版本端点,然后我在报表查看器中收到一个CORS错误。

无法访问Reporting REST服务。(serviceUrl = 'https://localhost:44398/api/reports')。确保服务地址正确,并在需要时启用CORS。(https://enable-cors.org)

运行Chrome,我检查F12网络选项卡,我看到一个名称"版本"状态为"CORS错误"。

检查报头:

General
Request URL: https://localhost:44398/api/reports/version
Request Method: GET
Status Code: 200 
Referrer Policy: strict-origin-when-cross-origin
Response Headers
access-control-allow-origin: *
content-type: application/json; charset=utf-8
date: Mon, 30 May 2022 14:10:10 GMT
server: Microsoft-IIS/10.0
x-powered-by: ASP.NET
Request Headers
:authority: localhost:44398
:method: GET
:path: /api/reports/version
:scheme: https
accept: application/json, text/javascript, */*; q=0.01
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
origin: http://localhost:1202
referer: http://localhost:1202/
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="101", "Google Chrome";v="101"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36

基于此,端点似乎是有效的,并且服务器的access-control-allow-origin允许所有。

我修改了服务器,特别允许http://localhost:1202也有相同的结果。

corsBuilder.WithOrigins("http://localhost:1202")
.AllowAnyMethod()
.AllowAnyHeader();

我还尝试了AlowAnyOrigin方法:

corsBuilder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
app.UseRouting();app.UseEndpoints()之间按照建议配置。

请求的状态码是200,即成功,这可能是正常的,即使发生了CORS错误,我不确定。

我可以尝试解决这个CORS错误吗?

选自如何在ASP.net Core WebAPI中启用CORS

我需要添加AllowCredentials().

在此过程中,我对原始代码进行了一些调整。我将所有CORS语句移到startup .cs方法的顶部,并将基于策略的CORS设置更改为更简单的非策略语法,但使其工作的是添加AllowCredentials()。

注意使用AllowCredentials()也不能使用AllAnyOrigin(),你必须使用WithOrigins()并分别指定。

public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllers().AddNewtonsoftJson();
services.AddRazorPages();
// Configure dependencies for ReportsController.
services.TryAddSingleton<IReportServiceConfiguration>(sp =>
new ReportServiceConfiguration
{
ReportingEngineConfiguration = sp.GetService<IConfiguration>(),
HostAppId = "Net5RestServiceWithCors",
Storage = new FileStorage(),
ReportSourceResolver = new UriReportSourceResolver(
System.IO.Path.Combine(sp.GetService<IWebHostEnvironment>().ContentRootPath, "Reports"))
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCors(
options => options.WithOrigins("http://localhost:1202").AllowAnyMethod().AllowAnyHeader().AllowCredentials()
);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapRazorPages();
});

}

老实说,我不知道为什么要这么难,只是说说而已。

相关内容