【问题标题】:How to enable CORS globally in ASP.NET web API core如何在 ASP.NET Web API 核心中全局启用 CORS
【发布时间】:2017-08-05 08:21:30
【问题描述】:

我找到了这个网站:

https://docs.microsoft.com/en-us/aspnet/core/security/cors

但是我对如何全局启用它感到困惑,因为似乎有两种方法可以做到这一点,这两种方法有什么区别?还是他们做两件不同的事情?

public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //https://docs.microsoft.com/en-us/aspnet/core/security/cors
            services.AddCors(options =>
            {
                options.AddPolicy("AllowSpecificOrigin",
                    builder => builder.WithOrigins("http://example.com")
                                        .AllowAnyHeader()
                    );
            });

            services.Configure<MvcOptions>(options =>
            {
                options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSpecificOrigin"));
            });

            // Add framework services.
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseCors("AllowSpecificOrigin");

            app.UseMvc();
        }

【问题讨论】:

  • Luis 为了清楚起见,您能否将您的代码块分成两种方式?
  • 您为什么将唯一的答案标记为正确,然后在其上悬赏从可信和/或官方来源寻找答案。
  • 这是一个错误,但我不知道如何纠正它。,我怎样才能删除赏金?

标签: c# asp.net asp.net-web-api asp.net-core asp.net-web-api2


【解决方案1】:

ConfigureServices 中的调用只是添加 Cors 服务,而不是设置它(包括创建 hte 策略)。通过添加过滤器,您可以使其成为全局过滤器,但我知道 UseCors(在配置中)是全局添加它的首选方式。过滤器代码所做的只是在所有控制器上强制属性,而 UseCors 有效地做同样的事情,只是在堆栈的不同部分。我相信 UseCors 将不仅仅用于 MVC 调用,这就是它与众不同的原因。

【讨论】:

    猜你喜欢
    • 2016-12-12
    • 2017-05-03
    • 2017-08-25
    • 2021-06-25
    • 2020-11-01
    • 2020-12-06
    • 2019-02-04
    • 2023-03-18
    • 1970-01-01
    相关资源
    最近更新 更多