在 ASP.NET Core 响应后做一些工作 [英] Do some work after the response in 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);
}
}
其中一个原因是我想调用一个网络服务(地理编码),它不需要回答,但可以很好地处理日志(我需要坐标的城市/国家).
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屋!