【问题标题】:405 (Method Not Allowed) and blocked by CORS policy405(方法不允许)并被 CORS 策略阻止
【发布时间】:2020-05-13 16:03:40
【问题描述】:

我在客户端有基于 Angular(7.2.1) 的 UI 的 Asp.Net Core(3) WebApi 项目。 当使用 Postman 或仅使用 URL 时,我可以使用 GET 和 POST 而不会出现任何特定错误。 当通过 Angular(Chrome\FireFox\IE Browser) 尝试相同的操作时,我收到以下错误。

zone.js:3243 OPTIONS http://localhost:8888/api/PaymentDetails 405 (Method Not Allowed) ccess to XMLHttpRequest at 'http://localhost:8888/api/PaymentDetails' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我将尝试分享尽可能多的代码来演示流程。

WebApi Startup.cs:

公共 IConfiguration 配置 { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{

    services.AddCors(options =>
    {
        options.AddPolicy("CorsPolicy",
            builder =>
            builder.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader()

                );
    });
    services.AddControllers()
        .AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
            options.JsonSerializerOptions.PropertyNamingPolicy = null;
        });

    services.AddDbContext<PaymentDetailContext>(options => options.UseSqlServer("Server=DESKTOP-KT0N2RN\\SQLEXPRESS;DataBase=PaymentDetailDB;Trusted_Connection=True;MultipleActiveResultSets=True;"));

}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{


    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });

    app.UseCors("CorsPolicy");
}

WebAPI GET 方法:

[HttpGet]
public async Task<ActionResult<IEnumerable<PaymentDetail>>> GetPaymentDetails()
{
    return await _context.PaymentDetails.ToListAsync();
}

客户端:

rootUrl: string = "http://localhost:8888/api";

getPaymentDetail()
{

    console.log(`${this.rootUrl}/PaymentDetails`)
    const headers = new HttpHeaders().set('Content-Type','application/json');
    // headers.append('Access-Control-Allow-Origin', '*');
    // headers.append('Access-Control-Allow-Headers','Origin, X-Requested-With, Content-Type, Accept');
    return this._http.get(`${this.rootUrl}/PaymentDetails`,{headers:headers});
}

【问题讨论】:

  • 我更新了我的答案,希望它现在能正确解决你的问题
  • 是的。这里的答案之一帮助我解决了这个问题。 app.UseCors() 必须在 app.UseMvc(); 之前;

标签: c# angular asp.net-core asp.net-core-webapi


【解决方案1】:

我认为在Startup Configure 中更改以下内容应该可行。注意顺序:根据文档

使用端点路由,CORS 中间件必须配置为在对 UseRouting 和 UseEndpoints 的调用之间执行。不正确的配置会导致中间件无法正常运行。

app.UseRouting();

app.UseAuthorization();

app.UseCors("CorsPolicy");

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

我认为对 COR 的快速总结可能有助于解释为什么邮递员请求对您有用。

浏览器默认使用CORS来检查哪些源服务器将接受来自的请求。

如果您对服务器的请求来自同一个来源(来源的所有部分必须匹配),您的 CORS 请求不会失败,因为它不是跨来源的。在您的情况下,端口不匹配,因此即使服务器和 Web 应用程序都从您的本地主机运行,它也算作跨源,因为端口不匹配

当您发送请求时,浏览器将首先发送选项请求(预检请求),该请求将显示支持的支持方法并检查您的源(您的前端 Web 应用程序)是否有权向服务器发送请求。此功能默认内置于大多数主流浏览器(Chrome、Firefox、Edge 等)。

您的邮递员请求有效,因为邮递员没有发送预检请求。

进一步阅读:

启用 CORS

https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1

什么是 CORS

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

【讨论】:

  • 问题是我在app.UseMvc之后使用了app.UseCors()
  • 很高兴你让它工作了。 app.UseMvc();不在 sn-p 中,所以当我提到订单时我把它省略了。有用的提示:总是调用 app.UseMvc();最后,这将有助于解决中间件问题
猜你喜欢
  • 1970-01-01
  • 2020-09-11
  • 2021-04-16
  • 2018-02-26
  • 2019-11-19
  • 2020-09-12
  • 2019-06-11
  • 2014-01-09
  • 2021-08-07
相关资源
最近更新 更多