【问题标题】:405 Method Not Allowed on ASP.NET 5 WebApi OPTIONS preflight405 方法不允许在 ASP.NET 5 WebApi OPTIONS 预检
【发布时间】:2021-03-01 22:51:08
【问题描述】:

我正在尝试在我的应用中集成 CORS 策略。 为此,我需要使用两个策略,因此我按照Enable CORS with Attributes 上的说明进行了以下操作。作为记录,我将 CORS 配置包装在一个扩展中,并从配置中加载列入白名单的端点。

    public static IServiceCollection ConfigureCors(this IServiceCollection serviceCollection,
        IConfiguration configuration)
    {
        return serviceCollection
                .AddCors(cors => cors.AddPolicy(CORS_POLICY_STRICT, policy =>
                    policy
                        .WithOrigins()
                        .WithMethods("POST")
                        .WithHeaders("Authorization")
                ))
                .AddCors(cors =>
                    cors.AddPolicy(CORS_POLICY_FE_API, policy =>
                        policy
                            .AllowAnyMethod()
                            .AllowAnyHeader()
                            .WithOrigins(GetFrontEndOrigins(configuration))
                    ))
            ;
    }


    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

           app
            .UseHttpsRedirection()
            .UseRouting()
            .UseCors()
            .UseAuthentication()
            .UseAuthorization()
            .UseEndpoints(endpoints => { endpoints.MapControllers(); })
            ;
    }


    public void ConfigureServices(IServiceCollection services)
    {
        services
            .ConfigureCors(Configuration)
            .AddControllers()
            ;
    }

CORS_POLICY_STRICT 应该是 BE-2-BE 调用的策略,而 CORS_POLICY_FE_API 必须登记 localhost 和 prod+dev FE 微服务 URL。

我在适当的地方用[EnableCors(<POLICY_NAME_CONST>)] 注释了控制器。

我的问题是应用程序启动时没有错误,Swagger 可以工作,但我什至不能在 cUrl/PowerShell 中运行预检请求,也不能从另一个端口(通常是 4200)部署在本地主机上的 Angular 应用程序调用代码.

提取任何带有EnableCorsAttribute 注释的API URL

> Invoke-RestMethod -Method Options -Uri "https://localhost:5001/api/v1/secure/SomeController/someMethod" -Headers @{"Access-Control-Request-Method"="POST";"Access-Control-Request-Headers"="X-Requested-With"}

$ curl -X OPTIONS "https://localhost:5001/api/v1/secure/SomeController/someMethod" -i   

两者都返回 405 Method Not Allowed

这有什么问题?

我还尝试将简单的UseCors() 调用替换为对UseCors(string) 的两次调用,每次调用都使用一个策略键。只有策略名称是参数,因为我将从服务配置策略。

【问题讨论】:

    标签: cors asp.net-core-webapi .net-5


    【解决方案1】:

    最终它起作用了,因为我在 http://localhost :4200 中配置了一个不需要的空间作为允许的来源之一

    【讨论】:

      猜你喜欢
      • 2016-05-06
      • 1970-01-01
      • 2019-09-22
      • 2017-07-04
      • 2016-12-03
      • 2019-07-28
      • 2014-05-21
      • 2014-08-19
      • 1970-01-01
      相关资源
      最近更新 更多