ASP.NET Core 配置跨域(CORS)

由于项目中需要实时消息,所以就使用了ASP.NET(Core) SignalR实时通讯库。因为业务服务与通讯服务是独立的,所以涉及到跨域的问题, 浏览器抛出的异常非常明显,这个是明显跨域相关内容。 报错信息如下:

CORS(跨域资源共享)是一种W3C标准,允许服务器放宽同源策略。使用CORS,服务器可以在显式允许某些跨域请求时拒绝其他跨域请求。CORS是相比其他跨域技术(比如JSONP)更安全、更灵活。

ASP.NET Core跨域问题需要再 StartUp.cs 文件中进行相关配置。

ConfigureServices方法增加内容

完整的ConfigureServices方法示例如下:

        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            //这里就是要加的代码
            services.AddCors(options => options.AddPolicy("CorsPolicy",
                builder =>
                {
                    builder.AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowAnyOrigin()
                        .AllowCredentials();
                }));

            services.AddMvc(options => { options.Filters.Add(); })
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
                //全局配置Json序列化处理
                .AddJsonOptions(options =>
                {
                    options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                })
                .AddFluentValidation();

            services.AddSignalR();

            return services.AutofacServiceProvider();
        }

  

在Configure方法中添加  app.UseCors("CorsPolicy");

完整Configure方法示例:

        public void Configure(IApplicationBuilder app, IHostingEnvironment env,
                              ILoggerFactory loggerFactory,
                              IOptions config)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            if (env.IsProduction())
            {
                //注册服务到consul
                app.UseConsul();

                using (HttpClient client = new HttpClient())
                {
                    StringContent content = new StringContent(JsonConvert.SerializeObject(config.Value.RegisterParams));
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    HttpResponseMessage message = client.PostAsync(config.Value.Server.Address, content).Result;
                };
            }
            app.UseCors("CorsPolicy");//特别注意:app.UseCors()必须放在app.UseMvc()之前。
            loggerFactory.AddNLog();
            env.ConfigureNLog("nlog.config");//读取Nlog配置文件
            app.UseSignalR(routes =>
            {
                routes.MapHub("/api/v1/examinations/messageHub");
            });
            app.UseMvc();
        }

  参考:https://www.skyfinder.cc/2020/01/13/aspnetcorecors/

原文地址:https://www.cnblogs.com/wolfocme110/p/13471671.html