Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return 404 from Async Task

I have this method in my mvc controller:

public ActionResult BlaBla()
{
    if (!ModelState.IsValid)
        return new HttpNotFoundResult();

    // ...
}

I want to create an Async version of it. So, I thought to change the code like this:

public async Task<ActionResult> BlaBla()
{
    if (!ModelState.IsValid)
        return new HttpNotFoundResult(); // Compiling error: this line is not working

    // ...
}

My question is how to return error codes (404, 500, ...) from my mvc controller, when using async Task<...> style?

like image 741
No1Lives4Ever Avatar asked Apr 09 '26 23:04

No1Lives4Ever


1 Answers

There must be a purpose when using an async action, right? Usually this purpose is to perform I/O bound operations such as remote TCP/HTTP calls which are exposed through an async service of yours.

In this, a typical controller action looks like this:

public async Task<ActionResult> BlaBla()
{
    if (!ModelState.IsValid)
    {
        return new HttpNotFoundResult();
    }

    MyViewModel model = await myService.GetTheModel();
    return View(model);
}

In this example, since you already have awaited for an async operation inside the method it will compile just fine. If you don't have any async operations then there's very little point of having an async action. It will do more damage then help. So now the question you should be asking yourself is: Do I really have some async services that can take advantage of I/O completion port to justify my need of using an async action?

like image 82
Darin Dimitrov Avatar answered Apr 12 '26 13:04

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!