我正在使用 SignalR 来使用 Angular 2 和 ASP.NET Core。
我有如下错误:
XMLHttpRequest 无法加载 http://localhost:55916/signalr//signalr/negotiate?clientProtocol=1.5&connectionData=%5B%7B%22name%22%3A%22event%22%7D%5D&_=1486394845411。 响应中“Access-Control-Allow-Origin”标头的值 当请求的凭据模式为时,不得为通配符“*” '包括'。因此不允许来源“http://localhost:8080” 使用权。发起请求的凭证模式 XMLHttpRequest 由 withCredentials 属性控制。
这是我的应用程序配置:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["data:secretKey"]));
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseCors(config =>
config.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
app.UseWebSockets();
app.UseSignalR("/signalr");
app.UseMvc();
}
我还有 Angular 2 SignalR 服务女巫
constructor(){
//setups...
this.connection = $.hubConnection(this.baseUrl + 'signalr/');
this.proxy = this.connection.createHubProxy(this.proxyName);
this.registerOnServerEvents();
this.startConnection();
}
注册服务器事件:
private registerOnServerEvents(): void {
this.proxy.on('FoodAdded', (data: any) => {
debugger;
this.foodchanged.emit(data);
});
this.proxy.on('FoodDeleted', (data: any) => {
debugger;
this.foodchanged.emit('this could be data');
});
this.proxy.on('FoodUpdated', (data: any) => {
debugger;
this.foodchanged.emit('this could be data');
});
this.proxy.on('SendMessage', (data: ChatMessage) => {
debugger;
console.log('received in SignalRService: ' + JSON.stringify(data));
this.messageReceived.emit(data);
});
this.proxy.on('newCpuValue', (data: number) => {
debugger;
this.newCpuValue.emit(data);
});
}
错误从一开始就开始了。
我想通了。在客户端设置连接时,我必须添加
有凭据
属性为 false
所以代码如下:
private startConnection(): void {
this.connection.start({ withCredentials: false }).done((data: any) => {
this.connectionEstablished.emit(true);
this.connectionExists = true;
}).fail((error: any) => this.connectionEstablished.emit(false));
}
这对我有用
app.UseCors(config => config.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials());
必须添加AllowCredentials选项
只要您的应用程序中使用了凭据安全性,您就应该指定 CORS 请求可能来自的域:
app.UseCors(config => config.WithOrigins("http://localhost:8080"));
如果您允许来自世界上任何域的 CORS 请求,凭据安全的价值就会大大降低。这就是错误消息告诉我们的内容。
在 .Net 7 中,如果您想使用 AllowAnyOrigin,您需要在 javascript 中将 withCredentials 属性设置为 false。
所以,下一个代码将在.Net 7 中运行。
.网络部分:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
builder.Services.AddSignalR(o =>
{
o.EnableDetailedErrors = true;
});
var app = builder.Build();
app.UseCors();
app.UseDefaultFiles();
app.UseStaticFiles();
app.MapHub<MessageHub>("/messageHub");
实例化连接的 JS 部分:
var connection = new signalR.HubConnectionBuilder()
.withUrl("URL_TO_SERVER/messageHub", { withCredentials: false })
.build();
因此,技巧是将选项 { withCredentials: false } 传递给 withUrl 方法。