自定义标头和信号器:Asp.Net MVC4 Web Api

 lw65112779 发布于 2023-02-11 19:09

我在我的asp.net mvc4 webapi项目中使用signalr(版本2.0.0),

这里允许跨源资源共享,我在webconfig文件中使用以下代码

 
    
    
  

以下是用于从服务器接收数据的客户端信号器代码:

 $(function () {
    var nodePublishingHub = $.connection.nodePublishingHub;
    nodePublishingHub.client.NodePublished = onNewMessage;

    $.connection.hub.error(function (error) {
        $('#messages').append('
  • ' + error + '
  • '); }); $.connection.hub.url = "http://localhost:5441/signalr"; $.connection.hub.start({ transport: 'longPolling' }) });

    我使用以下代码启用带信号器的CORS,

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

    但是会发生错误,

    XMLHttpRequest cannot load http://localhost:5441/signalr/negotiate?connectionData=%5B%7B%22name%22%3A%…name%22%3A%22nodepublishinghub%22%7D%5D&clientProtocol=1.3&_=1386654835296. The 'Access-Control-Allow-Origin' header contains the invalid value 'null, *'. Origin 'null' is therefore not allowed access.
    

    我该如何解决这个问题?请帮忙.

    我试过以下,

      我在golbal.asax中添加了这个代码,但它只会使每个方法交叉,所以我无法从服务器获取图像进行处理.

        HttpContext.Current.Response.Headers.Add("Access-Control-Allow-Origin", "*");
      

    小智.. 6

    不要修改signalr原始源代码.何时更新您的代码将停止工作.

    更喜欢这样:

    $.connection.hub.start({ withCredentials: false }).done(function () {
      //...
    }
    

    start({ withCredentials: false })而不是典型的start()将做的工作.你可以在这里验证(GitHub问题跟踪器)的官方支持.

    撰写答案
    今天,你开发时遇到什么问题呢?
    立即提问
    热门标签
    PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
    Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有