What is the proper way to send an HTTP 404 response from an ASP.NET MVC action?

前端 未结 6 693
春和景丽
春和景丽 2020-12-02 06:25

If given the route:

{FeedName}/{ItemPermalink}

ex: /Blog/Hello-World

If the item doesn\'t exist, I want to return a 404. What is the

6条回答
  •  悲哀的现实
    2020-12-02 06:46

    The HttpNotFoundResult is a great first step to what I am using. Returning an HttpNotFoundResult is good. Then the question is, what's next?

    I created an action filter called HandleNotFoundAttribute that then shows a 404 error page. Since it returns a view, you can create a special 404 view per controller, or let is use a default shared 404 view. This will even be called when a controller doesn't have the specified action present, because the framework throws an HttpException with a status code of 404.

    public class HandleNotFoundAttribute : ActionFilterAttribute, IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            var httpException = filterContext.Exception.GetBaseException() as HttpException;
            if (httpException != null && httpException.GetHttpCode() == (int)HttpStatusCode.NotFound)
            {
                filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; // Prevents IIS from intercepting the error and displaying its own content.
                filterContext.ExceptionHandled = true;
                filterContext.HttpContext.Response.StatusCode = (int) HttpStatusCode.NotFound;
                filterContext.Result = new ViewResult
                                            {
                                                ViewName = "404",
                                                ViewData = filterContext.Controller.ViewData,
                                                TempData = filterContext.Controller.TempData
                                            };
            }
        }
    }
    

提交回复
热议问题