user3037172
user3037172

Reputation: 587

Converting OwinHttpRequestContext to HttpContext? (IHttpHandler and websockets)

I am trying to implement web sockets in my application that currently implements a RESTful web API. I want certain pieces of information to be able to be exposed by a web socket connection so I am trying to figure out how to upgrade a normal HTTP request to a web socket connection.

I am trying to follow this tutorial

The problem I am having is my controller that handles the Get request inherits from ApiController and I am trying to do this:

 if (HttpContext.Current.IsWebSocketRequest)
    {
        HttpContext.Current.AcceptWebSocketRequest(SomeFunction);
    }
    return new HttpResponseMessage(HttpStatusCode.SwitchingProtocols);

The problem is my HttpContext.Current is always null and I do not know why. It seems like there is no such thing as a HttpContext. I do see however from the request that comes in that their is a HttpRequestContext that comes in with the request. Are these two objects related at all and is there any way I can get access to the .IsWebSocketRequest method so I can try and upgrade the request to a web socket connection?

My controller and what I am trying to do:

    [HttpGet]
    public HttpResponseMessage GetSomething()    
    {
        if (HttpContext.Current.IsWebSocketRequest()){
             Console.WriteLine("web socket request..");  
        }
    }

^ HttpContext.Current is always null. My controller inherits solely from ApiController

Upvotes: 13

Views: 2465

Answers (1)

Brian from state farm
Brian from state farm

Reputation: 2896

To get access to the Httpcontext in a MVC ApiController use this code.

        if (Request.Properties.ContainsKey("MS_HttpContext"))
        {
            HttpContextWrapper HttpContext = (HttpContextWrapper)Request.Properties["MS_HttpContext"];
            if (HttpContext != null)
            {
                if (HttpContext.IsWebSocketRequest)
                {
                    HttpContext.AcceptWebSocketRequest(SomeFunction);
                }
            }
        }

This will get the HttpContext out of the Request if it is supplied.

Upvotes: 3

Related Questions