Detecting async client disconnect in ASP.NET MVC

后端 未结 4 909
悲哀的现实
悲哀的现实 2020-12-09 04:51

Given an async controller:

public class MyController : AsyncController 
{
    [NoAsyncTimeout]
    public void MyActionAsync() { ... }

    public void MyAct         


        
相关标签:
4条回答
  • 2020-12-09 05:02

    It's just as @Darin says. HTTP is a stateless protocol which means that there are no way (by using HTTP) to detect if the client is still there or not. HTTP 1.0 closes the socket after each request, while HTTP/1.1 can keep it open for a while (a keep alive timeout can be set as a header). That a HTTP/1.1 client closes the socket (or the server for that matter) doesn't mean that the client has gone away, just that the socket hasn't been used for a while.

    There are something called COMET servers which are used to let client/server continue to "chat" over HTTP. Search for comet here at SO or on the net, there are several implementations available.

    0 讨论(0)
  • 2020-12-09 05:03

    For obvious reasons the server cannot be notified that the client has closed his browser. Or that he went to the toilet :-) What you could do is have the client continuously poll the server with AJAX requests at regular interval (window.setInterval) and if the server detects that it is no longer polled it means the client is no longer there.

    0 讨论(0)
  • 2020-12-09 05:06

    I realise this question is old, but it turned up frequently in my search for the same answer. The details below only apply to .Net 4.5

    HttpContext.Response.ClientDisconnectedToken is what you want. That will give you a CancellationToken you can pass to your async/await calls.

    public async Task<ActionResult> Index()
    {
        //The Connected Client 'manages' this token. 
        //HttpContext.Response.ClientDisconnectedToken.IsCancellationRequested will be set to true if the client disconnects
        try
        {
            using (var client = new System.Net.Http.HttpClient())
            {
                var url = "http://google.com";
                var html = await client.GetAsync(url,  HttpContext.Response.ClientDisconnectedToken);
            }
        }
        catch (TaskCanceledException e)
        {
            //The Client has gone
            //you can handle this and the request will keep on being processed, but no one is there to see the resonse
        }
        return View();
    }
    

    You can test the snippet above by putting a breakpoint at the start of the function then closing your browser window.


    And another snippet, not directly related to your question but useful all the same...

    You can also put a hard limit on the amount of time an action can execute for by using the AsyncTimeout attribute. To use this use add an additional parameter of type CancellationToken. This token will allow ASP.Net to time-out the request if execution takes too long.

    [AsyncTimeout(500)] //500ms
    public async Task<ActionResult> Index(CancellationToken cancel)
    {
        //ASP.Net manages the cancel token.
        //cancel.IsCancellationRequested will be set to true after 500ms
        try
        {
            using (var client = new System.Net.Http.HttpClient())
            {
                var url = "http://google.com";
                var html = await client.GetAsync(url, cancel);
            }
        }
        catch (TaskCanceledException e)
        {
            //ASP.Net has killed the request
            //Yellow Screen Of Death with System.TimeoutException
            //the return View() below wont render
        }
        return View();
    }
    

    You can test this one by putting a breakpoint at the start of the function (thus making the request take more than 500ms when the breakpoint is hit) then letting it run out.

    0 讨论(0)
  • 2020-12-09 05:24

    Does not Response.IsClientConnected work fairly well for this? I have just now tried out to in my case cancel large file uploads. By that I mean if a client abort their (in my case Ajax) requests I can see that in my Action. I am not saying it is 100% accurate but my small scale testing shows that the client browser aborts the request, and that the Action gets the correct response from IsClientConnected.

    0 讨论(0)
提交回复
热议问题