【问题标题】:Host WebSocket Server in ASP.NET WebAPI on Console Application在控制台应用程序上的 ASP.NET WebAPI 中托管 WebSocket 服务器
【发布时间】:2014-08-14 22:16:27
【问题描述】:

我已经构建了一个托管在控制台应用程序上的 ASP.NET WebAPI。我创建了一些 web apis 并且运行良好。然后我尝试在它上面实现web socket服务。服务器端代码如下

[RoutePrefix("api/notification")]
public class NotificationController : ApiController
{
    [HttpGet]
    [Route("")]
    public HttpResponseMessage Get()
    {
        if (HttpContext.Current.IsWebSocketRequest)
        {
            HttpContext.Current.AcceptWebSocketRequest(new NotificationWebSocketHandler());
            return Request.CreateResponse(HttpStatusCode.SwitchingProtocols);
        }
        else
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }
    }

    public class NotificationWebSocketHandler : WebSocketHandler
    {
        private static WebSocketCollection _clients;

        static NotificationWebSocketHandler()
        {
            _clients = new WebSocketCollection();

            Task.Factory.StartNew(() =>
                {
                    while (true)
                    {
                        Task.Delay(TimeSpan.FromSeconds(5));
                        if (_clients.Count > 0)
                        {
                            _clients.Broadcast(Guid.NewGuid().ToString());
                        }
                    }
                });
        }

        public override void OnOpen()
        {
            _clients.Add(this);
            Console.WriteLine("Web socket client opened, client count = {0}", _clients.Count);
        }

        public override void OnClose()
        {
            _clients.Remove(this);
            Console.WriteLine("Web socket client closed, client count = {0}", _clients.Count);
        }
    }
}

但是当我打开客户端页面(基于 AngularJS 构建)时,我收到了错误消息WebSocket connection to 'ws://10.222.115.220:8080/api/notification/' failed: Error during WebSocket handshake: Unexpected response code: 500

我的客户端代码是

app.shared.controllers.controller('DashboardCtrl', function ($q, $scope) {
    var ws = new WebSocket("ws://10.222.115.220:8080/api/notification/");
    ws.onopen = function () {
        console.log('web socket opened');
    }
    ws.onmessage = function (message) {
        $scope.seed = message;
    };

    $scope.seed = '(empty)';
});

当我附加调试并在 Get 函数的入口处添加断点时,我发现在没有命中此断点的情况下引发了错误 500。我认为这意味着错误是由 WebAPI 内部生成的。

我不确定我的代码是否有问题,或者 WebSocket 功能不支持控制台应用程序主机。

【问题讨论】:

    标签: angularjs asp.net-web-api websocket


    【解决方案1】:

    您在“Self Host”模式下使用 Web API? (托管在控制台中)

    您遇到的问题是对象 HttpContext.Current 为“null”。 这是自托管的问题。 HttpContext.Current 是在使用 IIS(网络托管)时设置的。此属性在自托管期间不可用。我认为这可能是你的问题。 (在您的 web-api-application 中引发 null-ref-exception 并返回 500 - internal server error)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多