5

Firstly, I know SignalR is the best websocket framework and i should use it instead of having fun with low level implementation.

But, Is there anyone who know how to correctly consume websocket in controller ? I am totally green.

Any good tutorial will be very helpful :)

I've tried do sth like this.

Middleware

 app.UseWebSockets();

 app.Use(async (context, next) =>
 {
        var http = (HttpContext)context;

        if (http.WebSockets.IsWebSocketRequest)
        {
         WebSocket webSocket = await http.WebSockets.AcceptWebSocketAsync();     
        }
         else
         {
            await next();
         }
 });
 //thanks to next(); app.UseMvc();

Controller

[Route("ws")]
    public class MonitorController : Controller
    {
        HttpContext context;
        WebSocket socket;

        public MonitorController(IHttpContextAccessor accessor)
        {
            this.context = accessor.HttpContext;
            if (!this.context.WebSockets.IsWebSocketRequest)
                throw new InvalidOperationException("incoming request is not a websocket request");
        }

        [HttpGet]
        public IActionResult Get()
        {
            return new MonitorWaiter(Wait);
        }
        .... some code MonitorWaiter.....

localhost:5000/ws

GET HTTP/1.1: 
Host: localhost:5000/ws
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13

During debugging it get into middleware but it skip controller.

Thanks a lot for some advices.


I saw it can be done by adding server to handler -> app.Use(); and in controller use some client implementation, but the question remains what when i want to create a few servers ?


Related post: Using WebSockets with ASP.NET Web API

I dont know if is it true but i think it should be used normally websocket handler than trying to do sth with api controller.

Community
  • 1
  • 1
patS
  • 61
  • 4
  • Can you be more specific about what you're trying to do? Your code as written should work, in a sense that your middleware handler will intercept any websocket requests (since you don't invoke `next()`, MVC will never see them), and you should be getting a usable `WebSocket` object. – Pavel Minaev Jul 30 '16 at 01:45

0 Answers0