Search code examples
asp.net-mvcasp.net-core

How to have .Net Core Action return Nothing or Redirect


Using .Net Core 2.2 I have several Controller actions that redirect to another action. More specifically there are several API calls, each one can fail or pass. If one passes, it will redirect to another Controller Action that executes the next API call.

If the API action returns a failure code, I don't want it to redirect instead I want to display the message to the user in the UI. To do so my action triggers a SignalR message that is picked up in the UI via javascript.

Which leads to my question,

Can an action in a Controller return nothing or something? By that I mean I want it to either redirect to another action, or not redirect or refresh the page at all. Essentially have it act like a Void function, that also has the ability to return.


Solution

  • You can define an action returns IActionResult and then return any result you need

    public IActionResult MultiAction()
    {
        ...
        if (failed)
        {
            return Json(new { message = "Error" });
        }
        else if (something)
        {
            return Redirect("/myurl");
        }
    
        return new NoContentResult();
    }