12

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

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
user3037172
  • 577
  • 1
  • 7
  • 25
  • Are you running this in a background thread? – Asad Saeeduddin Jun 08 '15 at 02:48
  • My thought was that maybe when the request comes in it may create a new thread for that specific request which is why it could be null. This is a project I just joined so I am not sure for sure. – user3037172 Jun 08 '15 at 02:56
  • Could you show the code for the full controller? We are using Web API and connecting very similar to your code and HttpContext.Current is not null. Also, are you customizing the controller selection? It's possible there is some custom code that is putting it on a background thread like @Asad mentioned or it could be re-using controllers rather than instantiating a new one. – ManOVision Jun 08 '15 at 05:45
  • Done. HttpContext is always null – user3037172 Jun 08 '15 at 14:00

1 Answers1

3

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.

Brian from state farm
  • 2,825
  • 12
  • 17