【问题标题】:How to fix CORS error: MethodDisallowedByPreflightResponse in ASP .NET C#如何修复 CORS 错误:ASP .NET C# 中的 MethodDisallowedByPreflightResponse
【发布时间】:2021-06-25 00:47:53
【问题描述】:

问题

向 ASP.NET Core API 服务器发送 http 请求(尽管我相信这将适用于各种不同的 .NET 样式服务器)我收到 CORS 错误:MethodDisallowedByPreflightResponse。我特别在 PUT 请求中收到此错误(它不会在 POST 或 GET 请求中发生)。

我尝试了什么:

  • 谷歌搜索,没有其他人写过这个特定错误。
  • DevTools Network 选项卡(即检查实际的 Http 请求标头和内容)...预检请求/响应中似乎没有任何内容表明允许哪些方法,哪些方法不允许。

【问题讨论】:

    标签: c# .net asp.net-core cors preflight


    【解决方案1】:

    我的回答:

    查看我服务器的 CORS 设置,我意识到 Cors 中间件上的 .AllowAnyHeader() 方法可能表明存在允许任何方法的类似方法。我是对的。

    使用.AllowAnyMethod() 修复此错误(假设您确实希望允许任何http 方法类型)。

    这是您专门将其放在服务器上的位置(我使用的是 ASP.NET CORE API,我相信是第 5 版):

    //Startup.cs
    
    //.... in the "Startup" class "ConfigureServices" method....
    public void ConfigureServices(IServiceCollection services)
            {
                services.AddCors(options =>
                {
                    options.AddDefaultPolicy(
                        builder =>
                        {
                            builder.WithOrigins("https://example.com")
                                .AllowAnyHeader()
                                .AllowAnyMethod(); //THIS LINE RIGHT HERE IS WHAT YOU NEED
                        });
                });
    
    // ... the rest of your code, other middleware, etc.
    

    【讨论】:

    • 不知道为什么这被否决了。回答帮我解决了同样的问题,谢谢!
    猜你喜欢
    • 2019-08-06
    • 2020-02-28
    • 2021-11-30
    • 2021-07-02
    • 2015-01-28
    • 2021-11-12
    • 2021-09-07
    • 1970-01-01
    • 2022-08-14
    相关资源
    最近更新 更多