ASP.Net MVC Controller Actions that return void

asp.netasp.net Mvc

asp.net Problem Overview


If I have the following controller action...

public void DoSomething()
{
}

will the framework actually convert it to this?

public EmptyResult DoSomething()
{
  return new EmptyResult();
}

asp.net Solutions


Solution 1 - asp.net

Yes

> A controller that returns void will produce an EmptyResult.

Taken from

The Life And Times of an ASP.NET MVC Controller

Solution 2 - asp.net

Seems so, check the source code of ControllerActionInvoker.cs. I haven't verified it, but logic tells me that a void return will set actionReturnValue to null, so an EmptyResult is generated. This is the most recent source code, haven't checked the source for ASP.net MVC 1.0.

protected virtual ActionResult CreateActionResult(ControllerContext controllerContext, ActionDescriptor actionDescriptor, object actionReturnValue) {
    if (actionReturnValue == null) {
        return new EmptyResult();
    }

    ActionResult actionResult = (actionReturnValue as ActionResult) ??
        new ContentResult { Content = Convert.ToString(actionReturnValue, CultureInfo.InvariantCulture) };
    return actionResult;
}

Solution 3 - asp.net

It won't "convert" it, but the two would have the same effect as far as the user is concern. A request would be sent, but no response would come back to the client.

Personally, I think you need to send some response back to the client, even if you just write a continue or success directly to the response stream. Even a JSON true, or an empty XML document is better than nothing at all.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChris ArnoldView Question on Stackoverflow
Solution 1 - asp.netMartijn LaarmanView Answer on Stackoverflow
Solution 2 - asp.netMichael StumView Answer on Stackoverflow
Solution 3 - asp.netJarrett MeyerView Answer on Stackoverflow