【发布时间】:2019-08-05 03:34:53
【问题描述】:
我正在使用 asp.net core 2.2 版本下的 asp.net core signalr 1.1.0。我想
为 Web 客户端和移动客户端发出跨域请求。
当我从 javascript 客户端发送请求时,此请求被阻止,并显示以下错误,
(索引):1 从源 'https://localhost:44381' 访问 XMLHttpRequest 在 'https://localhost:44373/chatHub/negotiate?token=12' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:'Access-Control-Allow 的值-当请求的凭据模式为“包含”时,响应中的“来源”标头不能是通配符“*”。 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()??
【问题讨论】:
-
您是否有任何商业案例希望允许任何来源?为您的原始配置设置一个 appsetting 字段应该不是问题。您还可以指定一个来源列表,这些来源也可以坚持到应用程序设置。这不适合你吗?
-
是的,我想为 web 和移动客户端使用 signalr 核心,所以对于移动客户端,我们不能给出任何来源?但是我怎样才能让它打开跨域连接。就像在 asp.net signalr 中一样
标签: c# asp.net-core asp.net-core-signalr