DEV Community

Dean Ashton
Dean Ashton

Posted on

Get your C# WebAPI controller to keep processing a request after returning 200 OK

Alt Text

Ever needed a "fire and forget" solution where a client calls a C# WebAPI controller that does something long running, but doesn't really care about the result?

For example, say you have a job scheduling system that runs a series of tasks and one of them is a call to a C# WebAPI service to create something like an export of data from a SQL Server table to a file.

Problem

The table is large and the export will tie up the job scheduling system from running the rest of the tasks in the process, or timeout the job scheduling process. And the result of the WebAPI service doesn't mean anything to the end result of the process, with the WebAPI reporting errors in another way such as by email.

Solution

Make the C# WebAPI report a HttpStatus code of 200 OK and say that the request is complete to the calling client, while still continuing to work on the request in the background.

For this fire and forget functionality, in your WebAPI controller, do this:

public async Task<IActionResult> Post(string id)
{
    try
    {
        return Ok("Request submitted successfully");
    }
    finally
    {
        Response.OnCompleted(async () =>
        {
            await DoProcessing(id);
        });
    }
}

The key is the "Response.OnCompleted" part, which allows your code to execute even after reporting HttpStatus 200 OK to the client.

Discussion (7)

Collapse
zoltanhalasz profile image
Zoltan Halasz

I have a similar situation in my webApi. The returned value is an entity , which needs long processing as the SQL query is complex (could take even 10-20 seconds). Is this a viable solution to return a value in the finally branch?

Collapse
deanashton profile image
Dean Ashton Author • Edited

Hi Zoltan, sorry for the late reply. Unfortinately I don't think so. This method ha already returned the result by the time you would finish processing. It's really only for things like exporting data to a file or sending a message in a queue for later processing (where the output of the processing is not returned to the caller)

In my case, the processing time for the longrunning task was 1 hour :)

Collapse
angrytoddlers profile image
AngryToddlers • Edited

Looks like the ideal solution to what I need. What usings do you have to have to get these commands ( Ok(obj) and Response.OnCompleted) available? I'm in .NET Core 3.1 and have these two (below) already and can't get these methods to build.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;

Collapse
angrytoddlers profile image
AngryToddlers

nm, I figured it out, I was foolishly editing the service file and not the controller file.

It still doesn't work how it seems like it should, I get the status code back almost immediately, but the response body still takes the same amount of time to return as it normally does.

Collapse
deanashton profile image
Dean Ashton Author

That's the purpose of this... to get a response back immediately to the caller of the controller with a 200 OK response. At that point the request is done. The API still keeps processing the code though, so it's great for things that don't return a result to the caller, such as outputting data to a file on the network, or processing large database tasks where the database holds the result.

For example, we have used it at work where the request happens as part of a pipeline of requests. The pipeline times out if any of the requests takes too long, and we needed to kick off a request that was very long running - it generates data in a database and runs for many hours. We didn't need to wait for the request to be finished though, because none of the other requests in the pipeline need it's output. So we kick off the request, get 200 OK response back to the caller, and then keep processing the rest of the request pipeline. The API still processes the request though, generating the data in the database.

Collapse
emctrder profile image
emctrder

I tried this solution but API is still waiting for process to complete before returning the response.

Collapse
shekarreddyb profile image
Shekar Reddy

Does this run on a new Threadpool thread after request is served?