在 ASP.NET MVC 中,当我的操作不会返回任何内容时,我使用 return new EmptyResult()
或返回null
有什么区别吗?
最佳答案
您可以返回null
。 MVC 将检测到这一点并返回一个 EmptyResult
。
MSDN: EmptyResult represents a result that doesn't do anything, like a controller action returning 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项目的源代码.
关于asp.net-mvc - 返回 new EmptyResult() VS 返回 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8561038/