.NetCore WebSocket跨域问题 SignalR CORS跨域

admin 发布时间:2021-09-17 分类:记事 阅读:2569次 添加评论

将 SignalR 集成到 ASP.NET Core api 程序的时候,按照官方 DEMO 配置完成,同域名访问没有问题,但是前端一直报跨域问题。原设置项:

  services.AddCors(op => { op.AddPolicy("cors", builder => { builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials(); }); });

出现该问题的原因是由于 CORS 策略设置不正确造成的,原始设置我是允许所有 Origin 来源,在正常跨域请求正常,在请求Websocket相关请求时候提示跨域错误。

但是由于 dotnetCore 2.2 的限制,无法使用 AllowAnyOrigin() + AllowCredentials() 的组合,只能显式指定 Origin 来源,或者通过下述方式来间接实现。

解决方案1,修改跨域配置:

 services.AddCors(op => { op.AddPolicy("cors", builder => { builder.SetIsOriginAllowed(origin => true).AllowAnyHeader().AllowAnyMethod().AllowCredentials(); }); });

解决方案2,直接采用中间件进行设置请求头:

public class CorsMiddleware
{
    private readonly RequestDelegate next;

    public CorsMiddleware(RequestDelegate next)
    {
        this.next = next;
    }
    public async Task Invoke(HttpContext context)
    {
        if (context.Request.Headers.ContainsKey(CorsConstants.Origin))
        {
            context.Response.Headers.Add("Access-Control-Allow-Origin", context.Request.Headers["Origin"]);
            context.Response.Headers.Add("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS,HEAD,PATCH");
            context.Response.Headers.Add("Access-Control-Allow-Headers", context.Request.Headers["Access-Control-Request-Headers"]);
            context.Response.Headers.Add("Access-Control-Allow-Credentials", "true");

            if (context.Request.Method.Equals("OPTIONS"))
            {
                context.Response.StatusCode = StatusCodes.Status200OK;
                return;
            }
        }
        await next(context);
    }
}
//在Configure方法中添加如下内容
app.UseMiddleware<CorsMiddleware>();


暂无留言

发表评论:

◎欢迎您的参与讨论。