在ASP.NET Core中做出响应后做一些工作 [英] Do some work after the response in ASP.NET Core

查看:91
本文介绍了在ASP.NET Core中做出响应后做一些工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用EFCore的ASP.NET Core网站。
我想做一些工作,例如登录到数据库,但是在将响应发送给用户以便更快回答之后。

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.

我可以做它在不同的线程中,但是由于对DbContext的异步访问,我不确定它是安全的。有建议的方法吗?

I could do it in a different thread, but due to async access of the DbContext I am not sure it is safe. Is there any recommended way to do that?

public async Task<IActionResult> Request([FromForm]RequestViewModel model, string returnUrl = null)
{
    try 
    {
      var newModel = new ResponseViewModel(model);
      // Some work 
      return View("RequestView",newModel)
    }
    finally
    {
        // Some analysis on the request
        // I would like to defer this part
        await Log(model);
    }
}

原因之一是我想打电话一种Web服务(地理编码),不需要回答,但可以在日志上正常工作(我需要坐标的城市/国家/地区)。

One of the reason is that I would like to call a web-service (geocoding), which is not needed to answer, but good to work on the log (I need the city/country of coordinates).

推荐答案

我看到这从未得到解答,但实际上有解决方案。
简单的解决方案:

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

public async Task<IActionResult> 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);
        });
    }
}

安全的解决方案,如 OnCompleted 过去曾在发送响应之前被调用,因此延迟了响应:

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<Task> callback)
{
    resp.OnCompleted(() =>
    {
        Task.Run(() => { try { callback.Invoke(); } catch {} });
        return Task.CompletedTask;
    });
}

并调用 Response.OnCompleted2(async()= > {/ *一些异步工作* /})

这篇关于在ASP.NET Core中做出响应后做一些工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆