开发者

Return HTTP 404 when MVC2 view does not exist

开发者 https://www.devze.com 2022-12-29 03:30 出处:网络
I just need to have the a small CMS-like controller. The easiest way would be something like this: public class HomeController : Controller {

I just need to have the a small CMS-like controller. The easiest way would be something like this:

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?
    }
}

The question is how to return HTTP 404 if the there is no view available?

Probably I can check the files in appropriate locations and cache the result, but that feels really dirty.

Thanks,

Dmitriy.


private bool ViewExists(string name) {
    return ViewEngines.Engines.FindView(
        ControllerContext, name, "").View != null;
}


The answer from Darin Dimitrov got me an idea.

I think it would be best to do just this:

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

having a new type of action result:

    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;      
        }

    }
0

精彩评论

暂无评论...
验证码 换一张
取 消