【问题标题】:Return HTTP 404 when MVC2 view does not exist当 MVC2 视图不存在时返回 HTTP 404
【发布时间】:2011-02-16 08:28:57
【问题描述】:

我只需要一个类似 CMS 的小型控制器。最简单的方法是这样的:

public class HomeController : Controller {
    public ActionResult View(string name) {
        if (!ViewExists(name))
            return new HttpNotFoundResult();
        return View(name);
    }

    private bool ViewExists(string name) {
        // How to check if the view exists without checking the file itself?
    }
}

问题是如果没有可用的视图,如何返回 HTTP 404?

也许我可以检查适当位置的文件并缓存结果,但感觉真的很脏。

谢谢,
德米特里。

【问题讨论】:

    标签: .net asp.net-mvc asp.net-mvc-2 view http-status-code-404


    【解决方案1】:
    private bool ViewExists(string name) {
        return ViewEngines.Engines.FindView(
            ControllerContext, name, "").View != null;
    }
    

    【讨论】:

    • 达林,太美了!这里要考虑的另一件事:已经有一个 ViewEngineResult 的实例如何重用它,以便 ViewResult 不会再次执行搜索?
    • 不用担心,在发布模式下编译时视图位置会被缓存。
    • 另外我相信以这种方式找到的视图应该被妥善处理。
    • 你会得到一个IView,它不是一次性的,但你有一个观点。
    • 达林,我想出了更好的解决方案。看我的回答。你帮助我达到了这一点。非常感谢。
    【解决方案2】:

    Darin Dimitrov 的回答让我有了一个想法。

    我认为最好这样做:

    public class HomeController : Controller {
        public ActionResult View(string name) {
            return new ViewResultWithHttpNotFound { ViewName = name};
        }
    }
    

    拥有一种新型的动作结果:

        public class ViewResultWithHttpNotFound : ViewResult {
    
            protected override ViewEngineResult FindView(ControllerContext context) {
                ViewEngineResult result = ViewEngineCollection.FindView(context, ViewName, MasterName);
                if (result.View == null)
                    throw new HttpException(404, "Not Found");
                return result;      
            }
    
        }
    

    【讨论】:

      猜你喜欢
      • 2015-01-03
      • 2018-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-15
      • 1970-01-01
      • 1970-01-01
      • 2016-04-07
      相关资源
      最近更新 更多