2

I have built an ASP.NET WebAPI which is hosted on a console application. There are some web apis I had created and worked well. Then I tried to implement web socket service on it. The server side code was like below

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

But when I opened the client page (which was built on AngularJS) I got the error message said WebSocket connection to 'ws://10.222.115.220:8080/api/notification/' failed: Error during WebSocket handshake: Unexpected response code: 500

My client side code was

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

When I attached debug and added a breakpoint at the entry of my Get function, and I found the error 500 was raised without this breakpoint hit. I think this means the error was generated by WebAPI internally.

I'm not sure if anything wrong in my code, or WebSocket feature doesn't support console application host.

1 Answer 1

3

you are using the Web API in "Self Host"-mode? (hosted in the console)

There you have the problem that the object HttpContext.Current is "null". This is a problem of self-hosting. HttpContext.Current is set while using the IIS (web-hosting). This property is not available during self-hosting. I think this could be your problem. (A null-ref-exception is thrown in your web-api-application and returns 500 - internal server error).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.