Do some work after the response in ASP.NET Core

前端 未结 5 1668
梦如初夏
梦如初夏 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 04:00

    I see this has never been answered, but actually have a solution. The simple solution:

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

    The secure solution, as OnCompleted used to be called before the response being sent, so delaying the response:

    public static void OnCompleted2(this HttpResponse resp, Func callback)
    {
        resp.OnCompleted(() =>
        {
            Task.Run(() => { try { callback.Invoke(); } catch {} });
            return Task.CompletedTask;
        });
    }
    

    and call Response.OnCompleted2(async () => { /* some async work */ })

提交回复
热议问题