【问题标题】:Cross Domain Negotiation request error with SignalRSignalR 的跨域协商请求错误
【发布时间】:2016-03-01 07:44:57
【问题描述】:

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

如果我在 PC 上使用 http://localhost:8080,我可以连接到 SignalR,而不是使用提到的 Url。

这里是启动类

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);
    });

对此的任何帮助将不胜感激。

【问题讨论】:

    标签: javascript c# asp.net-web-api signalr


    【解决方案1】:

    我在 web.config 中有它

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

    也许这也适合你。

    【讨论】:

    • 没问题,这不需要任何 nugget 包。但是使用 CORS 包,您可以在控制器/方法级别对其进行管理
    【解决方案2】:

    错误在这一行:

    app.UseCors(CorsOptions.AllowAll);
    

    会的

    map.UseCors(CorsOptions.AllowAll);
    

    【讨论】:

    • 我找不到 app.useCors 方法。
    • @Suresh 像app.UseCors("AllowAllOrigins");一样使用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-18
    • 2019-03-01
    • 1970-01-01
    • 2020-08-06
    • 1970-01-01
    • 2019-01-09
    • 2015-01-01
    相关资源
    最近更新 更多