Fire-forget and One-Way Calls in ASP.NET WebApi

8.1k views Asked by At

I totally understand that HTTP world is not the best choice for one-way calls and that WebApi is designed best for HTTP verbose communications. No doubt, WCF is the winner here. But, what if you already have an ApiController with a bunch of verbs exposed and at some point you needed to have a single one-way call too? And you don't want to host/maintain another service (WCF) for that.

Task<HttpResponseMessage> response = client.PostAsJsonAsync<Log>("api/log", log)

If you don't handle the response then you've got something similar to fire-and-forget. Is this the only way in WebApi or there's another solution?

2

There are 2 answers

7
Aliostad On

Your best bet is to start a new Task and send the response immediately rather than returning the task:

public void PostDoFireAndForget() // and NOT public Task PostDoFireAndForget()
    {
        Task.Factory.StartNew
            (() =>
                {
                    // ... start the operation here
                    // make sure you have an exception handler!!
                }

            );

    }
3
Darrel Miller On

Why not just call like this and ignore the returned task?

client.PostAsJsonAsync<Log>("api/log", log);

I do this with all my calls and use a handler in the response pipeline to deal with responses if necessary.