Do some work after the response in ASP.NET Core

前端 未结 5 1686
梦如初夏
梦如初夏 2021-02-08 03:31

I have an ASP.NET Core website, using EFCore. I would like to do some work like logging to the database, but after having sent the response to the user in order to answer faster

5条回答
  •  失恋的感觉
    2021-02-08 03:54

    Building on Jeans answer and a question and answer on the try - return - finally pattern, the try and finally blocks can be removed (if you don't really want to catch an exception).

    This leeds to the following code:

    public async Task Request([FromForm]RequestViewModel model, string returnUrl = null)
    {
        var newModel = new ResponseViewModel(model);
    
        // Some work 
    
        Response.OnCompleted(async () =>
        {
            // Do some work here
            await Log(model);
        });
    
        return View("RequestView",newModel);
    }
    

提交回复
热议问题