Web API 2返回OK响应,但在后台继续处理

Pet*_*ete 5 shopify asp.net-mvc-4 asp.net-web-api2

我已经为shopify创建了一个mvc web api 2 webhook:

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));
    }
}
Run Code Online (Sandbox Code Playgroud)

其中ProcessOrder循环遍历订单并将详细信息保存到我们的内部数据库.

但是,如果进程花费的时间太长,那么webhook会再次调用api,因为它认为它已经失败了.有没有办法先返回ok响应,然后再进行处理?

有点像在mvc控制器中返回重定向并且可以选择在重定向后继续处理其余操作.

请注意,我总是需要以Shopify的形式返回ok响应,如果它失败了19次,那么智慧决定删除webhook(并且处理时间过长会被视为失败)

Pet*_*ete 11

我设法通过使用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");
    }
Run Code Online (Sandbox Code Playgroud)

  • 在执行时,`ProcessOrder()`是否被随机终止,你还可以吗?因为这是你在ASP.NET工作进程中使用`Task.Run()`或任何其他类型的后台处理_打开的蠕虫.如果是这样,那么这就是要走的路.如果没有,请将工作卸载到专用程序,如Windows服务.阅读[@Vsevolod评论]中提供的链接(http://stackoverflow.com/questions/27060447/web-api-2-return-ok-response-but-continue-processing-in-the-background#comment42635506_27060447 ). (5认同)

Ser*_*gan 6

有几个选项可以实现此目的:

  1. 让任务运行程序喜欢HangfireQuartz运行实际的处理,您的 Web 请求将启动任务。
  2. 使用队列(如RabbitMQ)来运行实际进程,而 Web 请求只是向队列添加一条消息...请注意,这可能是最好的,但可能需要一些重要的设置知识。
  3. 虽然可能并不完全适用于您的具体情况,因为您正在让另一个进程等待请求返回...但如果您没有,您可以Javascript AJAX在后台使用启动进程,也许您可​​以关闭该请求的重试...仍然使请求在后台运行,所以可能不完全是您喜欢的。