【问题标题】:How to remove CORS restriction for one Controller Action in .net core 3.1如何在 .net core 3.1 中删除一个控制器操作的 CORS 限制
【发布时间】:2020-03-13 21:34:36
【问题描述】:

如何删除一个控制器操作的 CORS 限制

我已经为我的一个应用程序在一个地方为所有控制器/所有操作实施了 CORS。 但不知道如何取消对单个控制器的此限制

我在另一个地方的代码是

public static IWebHostBuilder BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args).
            ConfigureKestrel(serverOptions =>
            {
            }).UseIISIntegration()
            .UseStartup<StartupShutdownHandler>();
        private const string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

        public StartupShutdownHandler(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }        
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            CorsRelatedPolicyAddition(services);
            services.Configure<ForwardedHeadersOptions>(options =>
            {
                options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
            });        }

        private void CorsRelatedPolicyAddition(IServiceCollection services)
        {

                services.AddCors(options =>
                {
                    options.AddPolicy(MyAllowSpecificOrigins, builder => { builder.AllowedAnyOrigins().AllowAnyMethod().AllowAnyHeader(); });
                });

        }        
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime applicationLifetime)
        {...


            app.UseCors(MyAllowSpecificOrigins);

            ..

        }

【问题讨论】:

    标签: c# cors .net-core-3.1


    【解决方案1】:

    对于整个控制器(其中的所有方法)

    [EnableCors(origins: "http://www.example.com", headers: "*", methods: "*")]
     public class TestController : ApiController
     {
        // Controller methods not shown...
     }
    

    仅适用于特定方法

    [EnableCors(origins: "http://www.example.com", headers: "*", methods: "*")]
    public HttpResponseMessage GetItem(int id) { ... }
    

    更多详情请看link

    【讨论】:

    • 我没有限制来源。可能你的意思是 EnableCors 在行动。我是否需要在启动时添加任何东西?
    猜你喜欢
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多