首页 > 解决方案 > asp.net signalr core 中的跨域请求不起作用?

问题描述

我正在研究 asp.net core 2.2 版本下的 asp.net core signalr 1.1.0。我想
为 Web 客户端和移动客户端发出跨域请求。当我从 javascript 客户端发送请求时,此请求被阻止,并且以下错误显示,(index):1 Access to XMLHttpRequest at ' https://localhost:44373/chatHub/negotiate?token=12 ' from origin ' https:// /localhost:44381 '已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:响应中的“Access-Control-Allow-Origin”标头的值不能是通配符“*”时请求的凭据模式是“包含”。XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制。

我的 Javascript 客户端代码

var connection = new signalR.HubConnectionBuilder().withUrl("https://localhost:44373/chatHub?token="+12).build();

Signalr核心服务启动类代码

 // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder.AllowAnyOrigin()/*WithOrigins("https://localhost:44381")*/
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
            });

            services.AddSignalR();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            //services.AddCors();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }


            app.UseHttpsRedirection();
            app.UseCors("CorsPolicy");

            app.UseSignalR(routes =>
            {
                routes.MapHub<ChatHub>("/chatHub");
            });
            //app.UseStaticFiles();
            //app.UseCookiePolicy();
            app.UseMvc();
        }


builder.AllowAnyOrigin() its not working 

builder => builder.WithOrigins(" https://localhost:44381 ") 它的工作,但这是特定于这个 origin ,我想做 AllowAnyOrigin()??

标签: c#asp.net-coreasp.net-core-signalr

解决方案


我让它这样工作

在顶部配置服务

 services.AddCors();

并在配置方法中

 public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services
    .AddDbContext<ChatContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.Configure<FormOptions>(options =>
            {
                options.MultipartBodyLengthLimit = 60000000;
            });
            services.AddMvc().AddJsonOptions(options =>
            {
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            });

            services.AddMvcCore()
               .AddAuthorization()
               .AddJsonOptions(options =>
               {
                   options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                   options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
               });
            var identityServerAuthOptions = Configuration.GetSection("Identity").Get<IdentityServerAuthenticationOptions>();

            services.AddAuthentication("Bearer")
                .AddIdentityServerAuthentication(options =>
                {
                    options.Authority = identityServerAuthOptions.Authority;
                    options.RequireHttpsMetadata = identityServerAuthOptions.RequireHttpsMetadata;
                    options.ApiName = identityServerAuthOptions.ApiName;
                });


            var settings = new JsonSerializerSettings();
            settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            settings.ContractResolver= new CamelCasePropertyNamesContractResolver();
            services.AddSignalR()
                   .AddJsonProtocol(options => {
                       options.PayloadSerializerSettings = settings;
                          });
            services.AddTransient<IUserService, UserService>();
            services.AddCors();
    }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            //Data.AddData(app.ApplicationServices.GetService<ChatContext>());
            app.Use(async (context, next) =>
            {
                if (string.IsNullOrWhiteSpace(context.Request.Headers["Authorization"]))
                {
                    if (context.Request.QueryString.HasValue)
                    {
                        var token = context.Request.QueryString.Value.Split('&').SingleOrDefault(x => x.Contains("authorization"))?.Split('=')[1];
                        if (!string.IsNullOrWhiteSpace(token))
                        {
                            context.Request.Headers.Add("Authorization", new[] { $"Bearer {token}" });
                        }
                    }
                }
                await next.Invoke();
            });
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
              //  app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            app.UseAuthentication();
            app.UseCors(x => x.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials());
            app.UseSignalR(config =>
            {

                config.MapHub<UserHub>("/UsersHub");
            });
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
                routes.MapSpaFallbackRoute("spa-fallback", new { controller = "Home", action = "Index" });
            });
        }
    }





  app.UseCors(builder =>
            builder.AllowAnyOrigin()
       .AllowAnyMethod()
       .AllowAnyHeader()
           );

完整的代码可以在这里找到。这过去对我来说很好用。虽然最近没打开

Github 回购


推荐阅读