SignalR出现跨域协商请求错误

Cross Domain Negotiation request error with SignalR

本文关键字:协商 请求 错误 SignalR      更新时间:2023-09-26

我有一个ASP.NET Web Api项目,其中实现了SignalR。在Stratup类中我使用CorsOptions.AllowAll。在WebApiConfig类中,我还使用EnableCorsAttribute(""、""answers"*")。我在服务器位置发布了这个WebApi项目(http://192.168.9.6:3030)。但是在尝试使用$.hubConnection("http://192.168.9.6:3030/signalr")我从一个javascript客户端得到这样的消息:"协商请求时出错。"

如果我使用http://localhost:8080从我的电脑我可以连接到SignalR。

这是启动类

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.Map("/signalr", map =>
        {
            app.UseCors(CorsOptions.AllowAll);
            var hubConfiguration = new HubConfiguration();
            map.RunSignalR(hubConfiguration);
        });
    }
}

集线器级

public class SetupHub : Hub
{
    public void Send(string name, string message)
    {
        var msg = String.Format("{0}: {1} : {2}", name, message, DateTime.Now);
        Clients.All.addMessage(msg);            
    }
}

WebApiConfig类

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {   
        // Web API configuration and services
        var cors = new EnableCorsAttribute("*", "*", "*");
        //  config.EnableCors();
        config.EnableCors(cors);
        // Web API routes
        config.MapHttpAttributeRoutes();
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

全球ASAX

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
}

JavaScript客户端

var connection = $.hubConnection("http://192.168.9.6:3030/signalr");
var setupHubProxy = connection.createHubProxy('SetupHub');
setupHubProxy.on('addMessage', function (msg) {
    alert(msg);
});
connection.start()
        .done(function () {
            console.log('connected');
        })
    .fail(function (a) {
        console.log('not connected' + a);
    });

如有任何帮助,我们将不胜感激。

我在web.config 中有它

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
      </customHeaders>
    </httpProtocol>

也许这对你也有用。

错误在这一行:

app.UseCors(CorsOptions.AllowAll);

它将是

map.UseCors(CorsOptions.AllowAll);