return new EmptyResult() VS return NULL

2019-03-11 13:54发布

问题:

in ASP.NET MVC when my action will not return anything I use return new EmptyResult() or return null

is there any difference?

回答1:

You can return null. MVC will detect that and return a EmptyResult.

MSDN: EmptyResult represents a result that doesn't do anything, like a controller action returning null

Source code of mvc.

public class EmptyResult : ActionResult {

    private static readonly EmptyResult _singleton = new EmptyResult();

    internal static EmptyResult Instance {
        get {
            return _singleton;
        }
    }

    public override void ExecuteResult(ControllerContext context) {
    }
}

And the source from ControllerActionInvoker wich shows if you return null, MVC will return EmptyResult.

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;
}

You can download the source code of the Asp.Net Mvc Project on Codeplex.



回答2:

When you return null from an action the MVC framework (actually the ControllerActionInvoker class) will internally create a new EmptyResult. So finally an instance of the EmptyResult class will be used in both cases. So there is no real difference.

In my personal opinion return new EmptyResult() is better because it communicates more clearly that your action returns nothing.



回答3:

Artur,

both do basically the same in that the http header is sent back along with a blank page. you could however, tweak that further if you wished and return a new HttpStatusCodeResult() with the appropriate statusCode and statusDescription. i.e.:

var result = new HttpStatusCodeResult(999, "this didn't work as planned");
return result;

I think that may be a useful alternative.

[edit] - found a nice implementation of HttpStatusCodeResult() which exemplifies how to leverage this with google etc in mind:

http://weblogs.asp.net/gunnarpeipman/archive/2010/07/28/asp-net-mvc-3-using-httpstatuscoderesult.aspx