What's the difference between HttpContext.RequestAborted and CancellationToken parameter?

后端 未结 1 1539
南方客
南方客 2021-01-18 10:36

I\'m trying to create an async view component for ASP.NET Core 2.0. It will do an action that should be cancelled when the user navigates a

相关标签:
1条回答
  • 2021-01-18 11:32

    I know this is a 2 months old issue, but I have been struggling with this today too and came to some conclusions.


    What is the difference and what should I use?

    According to this thread these are exactly the same things. From CancellationTokenModelBinder source:

    var model = (object)bindingContext.HttpContext.RequestAborted;
    

    I can confirm, I always get the same values from HttpContext.RequestAborted and CancellationToken injection.

    Advantage of HttpContext.RequestAborted is that it is available in all controller's methods, not just actions. The CancellationToken parameter is IMHO better readable but if you have a number of nested methods that need to react to the token, it may become impractical to propagate it through their parameters. I would just use the one that better suits your needs.


    From the same thread, another post:

    This only works in 2.0 not in 1.x

    I know, this is not your case but it was mine.


    Finally, still from the same thread and especially discussion here, there's a problem in IIS (specifically in its interface with Kestrel). AFAIK you have to use Kestrel and optionally (mandatory for 1.x) a reverse proxy such as IIS, Apache or Nginx. I believe this is your case.


    Some quick testing: I created a project from Web API template using ASP .NET Core 2.0 and modified the first action in the controller it created:

    // GET api/values
    [HttpGet]
    public IEnumerable<string> Get(CancellationToken cancelToken)
    {
        Thread.Sleep(7000);
        cancelToken.ThrowIfCancellationRequested(); // breakpoint here
        return new string[] { "value1", "value2" };
    }
    

    Hit F5. It starts the app (including Kestrel) with IIS Express in front of it. Make the request and abort it (by closing a browser tab) before the 7 seconds. cancelToken.IsCancellationRequested is false when the breakpoint triggers.

    Now, change the debug profile from IIS Express to WebApplication1 (or whatever it is called):

    Everything works as expected for me.

    I did also try the same with ASP .NET Core 1.1 but with no success.


    AFAIK with ASP .NET Core 2.0, one should be able to use Kestrel on its own. I don't know if Apache or Nginx are doing better than IIS.

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