【问题标题】:return new EmptyResult() VS return NULL返回新的 EmptyResult() VS 返回 NULL
【发布时间】:2012-01-23 13:35:02
【问题描述】:

在 ASP.NET MVC 中,当我的操作不会返回任何我使用的东西时return new EmptyResult()return null

有什么不同吗?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 action


    【解决方案1】:

    您可以返回null。 MVC 将检测到并返回一个EmptyResult

    MSDN:EmptyResult 表示不执行任何操作的结果, 就像一个控制器动作返回 null

    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) {
        }
    }
    

    还有来自ControllerActionInvoker 的源代码,它显示您是否返回 null, MVC 将返回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;
    }
    

    您可以在Codeplex上下载Asp.Net MVC项目的源代码。

    【讨论】:

    • 内部单例是怎么回事?
    【解决方案2】:

    当您从操作返回 null 时,MVC 框架(实际上是 ControllerActionInvoker 类)将在内部创建一个新的 EmptyResult。所以最后EmptyResult 类的实例将在这两种情况下使用。所以没有真正的区别。

    在我个人看来,return new EmptyResult() 更好,因为它更清楚地传达了您的操作没有任何回报。

    【讨论】:

      【解决方案3】:

      阿图尔,

      两者的作用基本相同,因为 http 标头与空白页一起发回。但是,如果您愿意,您可以进一步调整它并返回一个带有适当状态代码和状态描述的新 HttpStatusCodeResult()。即:

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

      我认为这可能是一个有用的选择。

      [edit] - 找到了一个很好的 HttpStatusCodeResult() 实现,它举例说明了如何在考虑到 google 等的情况下利用它:

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

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-24
      • 2019-01-17
      • 2020-06-28
      • 1970-01-01
      相关资源
      最近更新 更多