随笔 - 432  文章 - 0  评论 - 15  阅读 - 63万

ASP.NET Core 配置跨域(CORS)

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

 

 

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

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

ConfigureServices方法增加内容

完整的ConfigureServices方法示例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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方法示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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/

posted on   狼来了  阅读(665)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
阅读排行:
· 10亿数据,如何做迁移?
· 推荐几款开源且免费的 .NET MAUI 组件库
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 易语言 —— 开山篇
· Trae初体验
历史上的今天:
2015-08-10 C#给图片加水印,可设置透明度
2015-08-10 C#图片水印类
2015-08-10 ASP.NET(C#)图片加文字、图片水印,神啊,看看吧
< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

点击右上角即可分享
微信分享提示