Web API 2返回OK响应,但在后台继续处理 [英] Web API 2 return OK response but continue processing in the background
问题描述
我已经为shopify创建了一个mvc web api 2 webhook:
I have create an mvc web api 2 webhook for shopify:
public class ShopifyController : ApiController
{
// PUT: api/Afilliate/SaveOrder
[ResponseType(typeof(string))]
public IHttpActionResult WebHook(ShopifyOrder order)
{
// need to return 202 response otherwise webhook is deleted
return Ok(ProcessOrder(order));
}
}
ProcessOrder
遍历订单并将详细信息保存到我们的内部数据库中.
Where ProcessOrder
loops through the order and saves the details to our internal database.
但是,如果该过程花费的时间太长,则Webhook会认为它已失败,因此再次调用api.有什么办法可以先返回ok
响应,然后再返回?
However if the process takes too long then the webhook calls the api again as it thinks it has failed. Is there any way to return the ok
response first but then do the processing after?
类似于在mvc控制器中返回重定向并可以选择在重定向后继续处理其余操作的情况.
Kind of like when you return a redirect in an mvc controller and have the option of continuing with processing the rest of the action after the redirect.
请注意,我将始终需要返回ok响应,因为Shopify明智地决定删除Webhook,如果它失败19次(并且处理时间过长则视为失败)
Please note that I will always need to return the ok response as Shopify in all it's wisdom has decided to delete the webhook if it fails 19 times (and processing too long is counted as a failure)
推荐答案
我设法通过使用Task
异步运行处理来解决我的问题:
I have managed to solve my problem by running the processing asynchronously by using Task
:
// PUT: api/Afilliate/SaveOrder
public IHttpActionResult WebHook(ShopifyOrder order)
{
// this should process the order asynchronously
var tasks = new[]
{
Task.Run(() => ProcessOrder(order))
};
// without the await here, this should be hit before the order processing is complete
return Ok("ok");
}
这篇关于Web API 2返回OK响应,但在后台继续处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!