2

I created a WebAPI method that will insert data into a database from the contents posted to the method.

My question is how can I push processing off so that the requester isn't hanging around for a response?

For example:

[HttpPost]
[Route("MyTest/ImportData")]
public HttpResponseMessage AddData([FromBody] XElement xmlBody)
{
    try
    {            
        // Verify that I can read the XML..

        // Push XML off to another process to insert into database.
        UpdateDataBase(xmlBody);

        // Notify requester that I accepted the file.
        return Request.CreateResponse(HttpStatusCode.OK);
    }
    catch (Exception ex)
    {
        return Request.CreateResponse(HttpStatusCode.InternalServerError);
    }
}

What I have works. However it may take up to 4 minutes to insert all of the data. I would like to verify that I can read the xml, push the process off somehow and give the user an OK response.

John Doe
  • 3,053
  • 17
  • 48
  • 75
  • 1
    Relevant, dupe: http://stackoverflow.com/questions/36335345/web-api-fire-and-forget – vcsjones Oct 19 '16 at 18:44
  • another common practice is to send your data to a queue so your method returns very quickly but the process monitoring the queue has all the time it needs. – Crowcoder Oct 19 '16 at 18:47
  • 1
    Commenting that you should return an HTTP 202 Accepted status code, not 200 OK. 202 indicates the work is not done yet, but has been accepted to be done at some point. – juunas Oct 19 '16 at 20:17

1 Answers1

2

Delegate the work to some other process.

It could be whatever you want, a service, a command line app, whatever is appropriate.

I would setup a messaging system, have the webapi send all these work actions to a queue and then have a windows service for example process this queue. This will release the pressure on the api and let it handle other requests without waiting for long running tasks to complete. It doesn't have to be anything more complicated than this.

As a suggestion, RabbitMQ is fairly straight forward, but I would suggest you look around and pick whatever you like

Andrei Dragotoniu
  • 6,155
  • 3
  • 18
  • 32