Asp.net mvc 返回新的EmptyResult()与返回NULL
在ASP.NET MVC中,当我的操作不会返回任何内容时,我使用Asp.net mvc 返回新的EmptyResult()与返回NULL,asp.net-mvc,asp.net-mvc-3,action,Asp.net Mvc,Asp.net Mvc 3,Action,在ASP.NET MVC中,当我的操作不会返回任何内容时,我使用返回新的EmptyResult() 或返回null 有什么区别吗?当您从操作返回null时,MVC框架(实际上是ControllerActionInvoker类)将在内部创建一个新的EmptyResult。最后,在这两种情况下都将使用EmptyResult类的实例。因此,没有真正的区别 我个人认为返回新的EmptyResult()更好,因为它能更清楚地传达您的操作不会返回任何结果 您可以返回null。MVC将检测到并返回一个Empt
返回新的EmptyResult()
或返回null
有什么区别吗?当您从操作返回
null
时,MVC框架(实际上是ControllerActionInvoker
类)将在内部创建一个新的EmptyResult
。最后,在这两种情况下都将使用EmptyResult
类的实例。因此,没有真正的区别
我个人认为
返回新的EmptyResult()
更好,因为它能更清楚地传达您的操作不会返回任何结果 您可以返回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;
}
MSDN:EmptyResult表示一个不起任何作用的结果,
就像控制器操作返回null一样
MVC的源代码。
以及来自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;
}
您可以在上下载Asp.Net MVC项目的源代码。Artur
两者的作用基本相同,http头随空白页一起发送回。但是,如果愿意,您可以进一步调整,并返回一个新的HttpStatusCodeResult(),其中包含适当的statusCode和statusDescription。i、 e:
var result = new HttpStatusCodeResult(999, "this didn't work as planned");
return result;
我认为这可能是一个有用的选择
[编辑]-找到了一个很好的HttpStatusCodeResult()实现,它举例说明了如何利用google等工具:
内部单例是什么?我喜欢你的方法,我必须补充一点,我们可以从这里使用一些预定义的代码