How to handle a "View not found" InvalidOperationException in asp.net mvc?

I have an asp.net mvc 1.0 site that serves some content from a level 2 hierarchy / Category / articles

When everything works correctly, the article is mapped to the view and the view is visualized. However, when the URL meets the routing condition, but the view does not exist, an exception occurs that cannot be blocked in the controller action.

Routing:

routes.MapRoute(
  "Article",
  "{category}/{article}.aspx",
  new { controller = "MyController", action = "Article" }
);

MyController action:

public ActionResult Article(string category, string article)
{
    string path = string.Format("~/Views/{0}/{1}.aspx", category, article);
    ViewResult vr = View(path);
    return vr;
}

However, when the view is not found, it is generated System.InvalidOperationException, which I cannot catch in the Action Controller.

: System.InvalidOperationException: '~/Views/my-category/my-article-with-long-name.aspx' . : ~/Views/-/-- name.aspx

Application_Error() global.asax.cs, :

  • ,
  • , , .
+5
4

xandy, Greg, . ( 404 aspnet mvc) , . , , Controller.OnException. , , OnException .

, , , , this.View .

, :)

protected override void OnException(ExceptionContext filterContext)
{
    //InvalidOperationException is thrown if the path to the view
    // cannot be resolved by the viewengine
    if (filterContext.Exception is InvalidOperationException)
    {
        filterContext.ExceptionHandled = true;
        filterContext.Result = View("~/Views/Error/NotFound.aspx");
        filterContext.HttpContext.Response.StatusCode = 404;
    }

    base.OnException(filterContext);
}

, , - NotFound . ErrorController NotFound Action. . , , HC .

+7

. ViewEngine, FileExists.

public class ViewEngine : RazorViewEngine
{
    protected override bool FileExists(ControllerContext context, string path)
    {
        if(!base.FileExists(context, path))
            throw new NotFoundException();

        return true;
    }

}

Global.asax ,

ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new ViewEngine());

Application_Error , NotFoundExceptions, , ErrorController.

+3

, , . , , ASP.net View ( , ).

, , - , , Server.MapPath(), , .

0

, , 404. , , .

AFAIK , , , ASPX , . ResolveURL Url.Content .

, , ( ) . ASPX - , , . - CMS (.. "" ), ASPX, , ASP.NET.

404, .

0

All Articles