c# - 如何在 ASP.NET Web API 核心中全局启用 CORS

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

我找到了这个网站:

https://learn.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://learn.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();
        }

最佳答案

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

关于c# - 如何在 ASP.NET Web API 核心中全局启用 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42795467/

相关文章:

asp.net - 在 Internet Explorer 中使用 asp.net 下载 .wav 文件

c# - JsonConvert.DeserializeObject 上的 StackOverflowException

c# - 使用 JSON.net 反序列化 JSON 流

c# - 获取表达式中成员的类型

c# - 改变 1 个 C# Controller 文件

c# - DataSelect导致错误DataSelect接受3个参数

c# - 运行时主机到底是什么?

c# - ASP.NET MVC 4 FileResult - 错误

c# - Entity Framework 6 投影生成 SQL 等效于 "Select *"并且不生成 WHERE 子句

asp.net - 如何更改 ASP.Net WebAPI 应用程序的根路径?