【发布时间】:2019-07-15 11:16:40
【问题描述】:
我和我的朋友在使用我们的 API 和 Angular 客户端时遇到了 CORS 问题。 我们正在尝试建立一个链接,我们正在使用 signalR 并且客户端(Angular 7)注册自己以接收来自服务器(ASP .NET core 2.2)的消息。
在浏览器控制台中,我收到了这条消息:
从源“http://localhost:4200”访问“https://ourEndpoint/CoordinatorHub/negotiate”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:“Access-Control-Allow-Origin”的值' 当请求的凭证模式为 'include' 时,响应中的标头不能是通配符 '*'。 XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制。
服务器端
我们的startup.cs看起来是这样的,我们已经关注了microsoft docs
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddDbContext<OneRoomContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("OneRoomContext")));
services.AddSignalR();
// Register the Swagger services
services.AddSwaggerDocument();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseDeveloperExceptionPage();
app.UseCors(builder =>
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
//if (env.IsDevelopment())
//{
// app.UseDeveloperExceptionPage();
// app.UseCors(builder =>
// builder.AllowAnyOrigin()
// .AllowAnyMethod()
// .AllowAnyHeader());
//}
//else
//{
// // 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.UseSignalR(route =>
{
route.MapHub<CoordinatorHub>("/CoordinatorHub");
});
app.UseHttpsRedirection();
app.UseMvc();
// Register the Swagger generator and the Swagger UI middlewares
app.UseSwagger();
app.UseSwaggerUi3();
}
这是我们的控制器:
using Microsoft.AspNetCore.SignalR;
using oneroom_api.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace oneroom_api.SignalR
{
public class CoordinatorHub : Hub
{
public Task SendNewUser(User user)
{
return Clients.All.SendAsync("GetNewUser", user);
}
}
}
Azure 门户:允许 CORS * 来源
客户端
这就是我们的 app.component.ts 的样子 (ngOnInit)
我们正在使用@aspnet/signalr 包
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl(localStorage.getItem('endpoint') + '/CoordinatorHub')
.build();
this.hubConnection.on('send', data => {
console.log(data);
});
this.hubConnection.start().then(() => this.hubConnection.invoke('send', 'Hello'));
如何禁用凭据模式或我需要在哪里提供 withCredentials 状态?
感谢您的时间和回答【问题讨论】:
-
@johnny5 不,在 Configure 方法中配置 CORS 没有任何问题。它绝对不会被弃用。在 ConfigureService 方法中配置 CORS 策略只是一种不同且更灵活的方式。请参阅 ASP.NET Core 2.2 的官方文档docs.microsoft.com/en-us/aspnet/core/security/…
标签: angular asp.net-core cors signalr