asp.net-mvc - 返回 new EmptyResult() VS 返回 NULL

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

在 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/

相关文章:

python - 强制即时 matplotlib 图形更新

c# - 为什么是 "Using asynchronous [...] methods on CPU-bound [providing] no benefits and results in more overhead."

c# - 需要有关 ASP.NET MVC 3 体系结构的一些指导

javascript - 如何在cshtml文件中调用外部javascript文件

asp.net-mvc-3 - 如何让 HTML.Partial 使用 T4MVC 常量?

asp.net-mvc-3 - 是否可以在Mono 2.10下运行ASP.NET MVC 3项目?

javascript - 将选择选项值传递到操作属性中,以便它可以作为 url 传递并打开网站

forms - 如何在GSP中找到从哪个 Controller Action 中调用它?

c# - csv 文件导入 Azure 存储时出现数据格式问题

asp.net-mvc - 在MVC Razor View 中的foreach循环中分组单选按钮?