return new EmptyResult() VS return NULL

2019-03-11 13:50发布

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

is there any difference?

3条回答
别忘想泡老子
2楼-- · 2019-03-11 13:58

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.

查看更多
smile是对你的礼貌
3楼-- · 2019-03-11 14:04

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.

查看更多
\"骚年 ilove
4楼-- · 2019-03-11 14:15

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

查看更多
登录 后发表回答