我正在使用angular 5和C#API,而我正在尝试实现SignalR以进行推送通知;并且我坚持这个错误"访问控制 - 允许 - 来源"
我在angular5
上使用ng-signalr我做错了什么,我不知道在哪里
startup.cs
using Owin;
using System.Web.Http;
using System.Web.Http.Cors;
using Microsoft.AspNet.SignalR;
namespace App5
{
public class Startup
{
// This code configures Web API. The Startup class is specified as a type
// parameter in the WebApp.Start method.
public void Configuration(IAppBuilder appBuilder)
{
// Configure Web API for self-host.
HttpConfiguration config = new HttpConfiguration();
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
// Enable attribute based routing
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}/{action}/{code}",
defaults: new { id = RouteParameter.Optional , action = RouteParameter.Optional, code = RouteParameter.Optional}
);
appBuilder.UseWebApi(config);
appBuilder.MapSignalR();
}
}
}
Ng2SignalRHub.cs
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace App5
{
[Authorize]
[HubName("Ng2SignalRHub")]
public class Ng2SignalRHub : Hub
{
public override Task OnConnected()
{
Trace.TraceInformation("Ng2SignalRHub - OnConnected");
var user = GetAuthenticatedUser();
Clients.All.OnUserConnected(user);
return base.OnConnected();
}
private string GetAuthenticatedUser()
{
var username = Context.QueryString["user"];
if (string.IsNullOrWhiteSpace(username))
throw new System.Exception("Failed to authenticate user.");
Trace.TraceInformation("GetAuthenticatedUser :" + username);
return username;
}
}
}
请任何人都可以解决此问题 提前谢谢
答案 0 :(得分:0)
请查看此链接,看看是否有帮助:https://github.com/aspnet/SignalR/issues/1400
由于SignalR是使用asp.net core 2.1预览的,因此您必须确保所有版本的客户端软件包都匹配。您还应该配置CORS策略
在ConfigureServices中:
services.AddCors(options => options.AddPolicy("CorsPolicy", builder =>
{
builder
.AllowAnyMethod()
.AllowAnyHeader()
.WithOrigins("http://localhost:50000");
}));
services.AddSignalR();
在配置中:
app.UseCors("CorsPolicy");