我想回答一个请求,但要继续处理代码。
我试过类似的方法:
[HttpPost]
public async Task<HttpResponseMessage> SendAsync(MyRequest sms)
{
await Task.Run(() => Process(sms)); //need to run in a separate thread
var response = new MyRequest(sms) { Ack = true };
return Request.CreateResponse(HttpStatusCode.Created, response.ToString());
}
private async void Process(MyRequest sms)
{
var validationResult = new MyRequestValidation(_p2pContext, _carrierService).Validate(sms);
if (string.IsNullOrWhiteSpace(validationResult.Errors[0].PropertyName)) // Request not valid
return;
Message msg;
if (validationResult.IsValid)
{
msg = await _messageService.ProcessAsync(sms);
}
else // Create message as finished
{
msg = _messageService.MessageFromMyRequest(sms,
finished: true,
withEventSource: validationResult.Errors[0].CustomState.ToString()
);
}
// Salve in db
_p2pContext.MessageRepository.Create(msg);
_p2pContext.Save();
}
最佳答案
I would like to answer a request, but continue processing code.
您确定要在 ASP.NET 中执行此操作吗?这不是 ASP.NET(或任何 Web 服务器)旨在处理的情况。
执行此操作的经典(正确)方法是将工作排队到持久队列中,并让单独的后端进程对该工作进行实际处理。
在请求上下文之外的 ASP.NET 内部进行处理存在各种危险。通常,您不能假设工作会真正完成。如果您不介意(或者只是喜欢危险地生活),那么您可以使用 HostingEnvironment.QueueBackgroundWorkItem
。
我有一个 blog post更详细。
关于c# - 如何回答请求但继续处理 WebApi 中的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25274096/