覆盖全局CORS策略,对signalR端点采用不同的策略。

问题描述 投票:0回答:1

我有一个适用于所有端点的全局CORS策略,但我想为signalR集线器端点覆盖这个策略。

下面是我的ConfigureServices方法,它有一个全局的CORS策略,我不能修改。

    public void ConfigureServices(IServiceCollection services)
    {    
       // some piece of code before adding CORS

        services.AddCors(o =>
        {
            o.AddDefaultPolicy(p =>
            {
                p.AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod();
            });
        });

        // some piece of code after adding CORS
    }

下面是配置方法

    public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider)
    {
        app.UseCors();
        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endPoints =>
        {
            endPoints.MapControllers();
            endPoints.MapHub<NotificationHub>("/notificationHub")
            .RequireCors((builder) =>
            {
                builder
                .WithOrigins(_configuration.GetValue<string>("Settings:ClientAppUrl"))
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials();
            });
        });
    }

很明显,我已经覆盖了信号的特定端点即notificationHub的CORS策略。

我在浏览器中得到了相同的CORS错误,因为我在为notificationHubnegotiate添加CORS策略之前得到了

对飞行前请求的响应没有通过访问控制检查。响应中'Access-Control-Allow->Credentials'头的值是'',当请求的凭证模式是>'include'时,它必须是'true'。XMLHttpRequest发起的请求的凭证模式由>withCredentials属性控制。

另外请注意,如果我在全局CORS策略中添加AllowCredentials()方法,那么signalR可以正常工作,但我的目标是只为signalR端点添加新的CORS策略。

我没有使用OWIN CORS,只是使用Microsoft.AspNetCore.Cors。

c# asp.net-core cors signalr startup
1个回答
1
投票

我已经找到了修复的方法。它很简单,但经常被忽略。

中间件的顺序在这里很重要。通过调换下面两个中间件,我让它工作了。

旧的

app.UseCors();
app.UseRouting();

新产品

app.UseRouting();
app.UseCors();

如果有人遇到这个问题,可以试试这样做。一定会成功的。

这个 文档 来自微软的支持这一说法。

© www.soinside.com 2019 - 2024. All rights reserved.