C# CORS飞行前请求被阻止.Net Core 2.2

C# CORS飞行前请求被阻止.Net Core 2.2,c#,angular,.net-core,cors,.net-core-2.2,C#,Angular,.net Core,Cors,.net Core 2.2,我正试图从我的角度前端向加拿大邮政局请求获取速率API。不幸的是,我的后端.NETCore2.2似乎阻止了所有的飞行前请求。如果我尝试使用禁用web安全标志的chrome浏览器发出这些请求,我可以完成请求,但不幸的是,在正常浏览时,我无法完成请求。我在这里读了很多文章,并在.NET文档中指定了cors异常,但似乎飞行前的请求仍然被阻止 错误消息: 访问位于“”的XMLHttpRequesthttps://soa-gw.canadapost.ca/rs/ship/price“起源”http://l

我正试图从我的角度前端向加拿大邮政局请求获取速率API。不幸的是,我的后端.NETCore2.2似乎阻止了所有的飞行前请求。如果我尝试使用禁用web安全标志的chrome浏览器发出这些请求,我可以完成请求,但不幸的是,在正常浏览时,我无法完成请求。我在这里读了很多文章,并在.NET文档中指定了cors异常,但似乎飞行前的请求仍然被阻止

错误消息: 访问位于“”的XMLHttpRequesthttps://soa-gw.canadapost.ca/rs/ship/price“起源”http://localhost:4200'已被CORS策略阻止:对飞行前请求的响应未通过访问控制检查:它没有HTTP ok状态

我提到的一些文档没有成功,我尝试向C#添加额外的cors权限,但飞行前请求仍然被阻止。

我也无法修改前端http头以删除飞行前检查,因为其中一些是加拿大邮政api所必需的。

前端呼叫

        const httpOptions = {
                    headers: new HttpHeaders({
                      'Content-Type':  'application/vnd.cpc.ship.rate-v4+xml', //<- To SEND XML
                      'Accept':  'application/vnd.cpc.ship.rate-v4+xml',       //<- To ask for XML                                 //<- b/c Angular understands text
                      'Authorization': 'Basic YTUxZGQ1MWY2YjJhNjE4ODowODgzOThiZTUxY2Y4Y2RjZTIzM34',
                      'Accept-language': 'en-CA',
                      'Access-Control-Allow-Origin': '*',
                      "Access-Control-Allow-Methods": "DELETE, POST, GET, OPTIONS",
                    }),
                     
                    responseType: 'text' as 'json'
                  };

    var  postedData = `
                    <mailing-scenario xmlns="https://www.canadapost.ca/ws/ship/rate-v4">
                    <customer-number>0009669089</customer-number>
                    <parcel-characteristics>
                    <weight>5 </weight>
                    </parcel-characteristics>
                    <origin-postal-code>M5V0G1</origin-postal-code>
                    <destination>
                    <domestic>
                    <postal-code>M4R1L8</postal-code>
                    </domestic>
                    </destination>
                    </mailing-scenario>
                    `;
// http post to canada post using angular httpclient
         this.http.post('https://soa-gw.canadapost.ca/rs/ship/price', postedData, httpOptions)
                    .subscribe(
                      result => {    
                console.log(result);                 
                      }, 
                      error => console.log('There was an error: ', error));
const httpOptions={
标题:新的HttpHeaders({
“内容类型”:“application/vnd.cpc.ship.rate-v4+xml”//
{
options.AddDefaultPolicy(
生成器=>
{
建筑商。带原产地(“*”)
.AllowAnyHeader()
.AllowAnyMethod();
});
options.AddPolicy(“MyAllowlHeadersPolicy”,
生成器=>
{
builder.WithOrigins(“*”).AllowAnyMethod()
.AllowAnyHeader();
});
});
配置(选项=>
{
//此lambda确定给定请求是否需要非必要cookie的用户同意。
options.checkApprovered=context=>false;
options.MinimumSameSitePolicy=SameSiteMode.None;
});
services.AddSwaggerDocument();
services.AddDbContext(选项=>
options.UseSqlServer(Configuration.GetConnectionString(“DefaultConnection”),
providerOptions=>providerOptions.EnableRetryOnFailure());
services.AddDefaultIdentity()
.AddRoles()
.AddEntityFrameworkStores();
///自动映射器配置
var mappingConfig=新的MapperConfiguration(mc=>
{
mc.AddProfile(新的MappingProfile());
});
IMapper mapper=mappingConfig.CreateMapper();
服务。AddSingleton(映射器);
配置存储库(服务);
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.Configure(Configuration.GetSection(“设置”));
services.AddMvc().AddJsonOptions(选项=>
{
options.SerializerSettings.ReferenceLoopHandling=ReferenceLoopHandling.Ignore;
options.SerializerSettings.NullValueHandling=NullValueHandling.Ignore;
options.SerializerSettings.MissingMemberHandling=MissingMemberHandling.Ignore;
});
配置(选项=>
{
options.MemoryBufferThreshold=Int32.MaxValue;
});
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
公共无效配置(IApplicationBuilder应用程序,IHostingEnvironment环境)
{
应用程序UseCors(“MyAllowlHeadersPolicy”);
app.UseOpenApi();
app.UseSwaggerUi3();
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
其他的
{
app.UseExceptionHandler(“/Home/Error”);
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(路由=>
{
routes.MapRoute(
名称:“默认”,
模板:“{controller=Home}/{action=Index}/{id?}”);
});
app.UseSpa(spa=>
{
});
}
专用void配置存储库(IServiceCollection服务)
{
///存储库注入
services.addScope();
services.addScope();
services.addScope();
services.addScope();
services.addScope();
services.addScope();
services.addScope();
services.addScope();
}
}
}

解决方案:若要从生产系统发送消息,前端飞行前请求被阻止,请改为从后端服务器发送api调用。尽管在现场使用web security disable进行测试,但它必须从后端发送。

在一些CORS内容上也有同样的问题,出于测试目的,我只添加了这些行以使其正常工作。从长远来看,这可能不是最好的,但是。它可能会让它运行起来。在启动中的ConfigureServices中添加以下内容:

services.AddCors();
 app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
然后在配置中添加以下内容:

services.AddCors();
 app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
我把services.AddCors();在ConfigureServices和app.UserCors的顶部。。。中间的app.UseRouting();和app.UseAuthorization()


希望这对您有用。

我尝试过,但仍然有相同的飞行前错误消息。在我的应用程序中,我没有对app.UseRouting()的调用;或App.UseAuthorization();你会把它放在什么地方?我已经试过了