简体   繁体   English

如何在 .net core 3.1 中删除一个 Controller Action 的 CORS 限制

[英]How to remove CORS restriction for one Controller Action in .net core 3.1

How to remove CORS restriction for one Controller Action如何删除一个控制器操作的 CORS 限制

I have implemented CORS for one of my application for all controllers/ all action at one place.我已经在一个地方为所有控制器/所有操作的应用程序之一实施了 CORS。 But don't know how to remove this restriction for just single controller但不知道如何仅针对单个控制器取消此限制

My code for one other place is我在另一个地方的代码是

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);

            ..

        }

For entire controller (all the method in it)对于整个控制器(其中的所有方法)

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

For a particular method only仅针对特定方法

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

For more detail see this link有关更多详细信息,请参阅此链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM