404 Http error handler in Asp.Net MVC (RC 5)

那年仲夏 提交于 2019-11-26 09:23:49

问题


How can I Handler 404 errors without the framework throwing an Exception 500 error code?


回答1:


http://jason.whitehorn.ws/2008/06/17/Friendly-404-Errors-In-ASPNET-MVC.aspx gives the following explanation:

Add a wildcard routing rule as your final rule:

routes.MapRoute("Error", 
                "{*url}", 
                new { controller = "Error", action = "Http404" });

Any request that doesn't match another rule gets routed to the Http404 action of the Error controller, which you also need to configure:

public ActionResult Http404(string url) {
    Response.StatusCode = 404;
    ViewData["url"] = url;
    return View();
}



回答2:


You can also override HandleUnknownAction within your controller in the cases where a request does match a controller, but doesn't match an action. The default implementation does raise a 404 error.




回答3:


throw new HttpException(404, "Resource Not Found");




回答4:


With MVC 3 you can return HttpNotFound() to properly return a 404.

Like this:

public ActionResult Download(string fontName)
{
    FontCache.InitalizeFonts();

    fontName = HttpUtility.UrlDecode(fontName);

    var font = FontCache.GetFontByName(fontName);
    if (font == null)
        return HttpNotFound();

    return View(font);
}


来源:https://stackoverflow.com/questions/108813/404-http-error-handler-in-asp-net-mvc-rc-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!