Web API 2 return OK response but continue processing in the background

女生的网名这么多〃 提交于 2019-12-23 11:53:38

问题


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));
    }
}

Where ProcessOrder loops through the order and saves the details to our internal database.

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?

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.

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)


回答1:


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");
    }


来源:https://stackoverflow.com/questions/27060447/web-api-2-return-ok-response-but-continue-processing-in-the-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!