【发布时间】:2020-08-23 23:49:13
【问题描述】:
我在 Angular 8 和 ASP.NET Web API、.NET Framework 4.7.2 之间有 SignalR 通信,它工作正常。但是我已经有几个月没有测试过了,现在当我尝试时,我在浏览器控制台中得到了这个结果:
http://localhost:55454/signalr/negotiate? .... net::ERR_ABORTED 404(未找到)
这几个月唯一的主要变化是现在我的 API 使用 Identity Server 3,但我认为这不是问题。
然而,这是我在实施 Identity Server 之前在 StartUp 中的代码:
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
EnableJSONP = true,
EnableDetailedErrors = true,
};
map.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
{
Provider = new QueryStringOAuthBearerProvider(),
AccessTokenProvider = new AuthenticationTokenProvider()
{
OnCreate = new Action<AuthenticationTokenCreateContext>(c =>
{
c.SetToken(c.SerializeTicket());
}),
OnReceive = new Action<AuthenticationTokenReceiveContext>(c =>
{
c.DeserializeTicket(c.Token);
c.OwinContext.Environment["Properties"] = c.Ticket.Properties;
})
},
});
map.RunSignalR(hubConfiguration);
});
还有 QueryStringOAuthBearerProvider(因为我在查询字符串中发送了令牌):
private class QueryStringOAuthBearerProvider : OAuthBearerAuthenticationProvider
{
public override Task RequestToken(OAuthRequestTokenContext context)
{
if (context != null)
{
var value = context.Request.Query.Get("token");
if (!string.IsNullOrEmpty(value))
{
context.Token = value;
}
}
return Task.FromResult<object>(null);
}
}
我尝试了新的代码,但结果还是一样:
app.UseIdentityServerBearerTokenAuthentication(new
IdentityServerBearerTokenAuthenticationOptions
{
Authority = identityAuthority,
});
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
EnableJSONP = true,
EnableDetailedErrors = true,
};
map.UseIdentityServerBearerTokenAuthentication(new IdentityServer3.AccessTokenValidation.IdentityServerBearerTokenAuthenticationOptions
{
Authority = identityAuthority,
TokenProvider = new QueryStringOAuthBearerProvider(),
});
map.RunSignalR(hubConfiguration);
});
}
我认为这不是主要问题,因为在 Debug 中它永远不会遇到 QueryStringOAuthBearerProvider 类中的断点。它必须是。
我在 API 中的 SignalR 版本是 2.4.1,所以它在 Angular ("signalr": "^2.4.1",) 我还使用 "ng2-signalr": "^8.0.2" nuget 来保存一些手动编写的 JS 代码。
这是 Typescript 中的一个示例(以前可以使用):
startConnection(hubConnection: SignalR): Promise<ISignalRConnection> {
console.log('Connecting...');
if (this.authService && this.authService.token) {
return hubConnection.connect({ jsonp: true, hubName: 'ChatHub', url: this.config.API_BASE_URL, qs: { token: this.authService.token } });
}
}
也许是启动配置,但也许不是因为它看起来根本找不到这样的地址(localhost/signalr ...) 此 Angular 项目的 CORS 策略已设置,所有其他常规 API 调用都可以正常工作。
我不明白为什么我从不久前作为魅力的某些功能中引发了这个 404 错误。
编辑:
在数据库中,我保留了 Angular 应用程序的本地主机地址,并为他提供了完整的 CORS 访问权限,但这对于 SignalR 来说是否足够?是的,请求来自同一个本地主机,但不调用http://localhost:55454/api,而是调用http://localhost:55454/signalr,那么是否应该对CORS 做一些额外的事情?我认为它可能应该,否则为什么要添加这行旧代码:
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
有什么困难吗?
【问题讨论】:
-
我相信您应该在映射集线器之前配置 CORS。
-
这个 CORS 配置来自旧实现,因为使用 Identity Server 3 我将 CORS 来源保存在数据库中自己的表中
标签: .net angular asp.net-web-api signalr