Setting HTTP status in the results of an ASP.NET MVC controller does not display a view

I have a custom ActionResult to return specific HTTP errors, such as NotFoundResult and ForbiddenResult, all of which come from ViewResult.

I use them for instances, for example, for short circuits with 404, if the entity was not found in the database during the action.

In these result objects, I set the HTTP status to the corresponding number. When I do this, the view that the ViewResults link is not showing. I need to leave the status 200 OK so that my view is displayed.

How to set the appropriate status and visualize a view in ASP.NET MVC 2.0?

+6
asp.net-mvc
source share
1 answer

I have a custom ActionResult to return some HTTP errors like NotFoundResult and ForbiddenResult, all of which come from ViewResult.

Let me offer you alternative error handling:

Start by creating an error controller and corresponding views:

public class ErrorController : Controller { public ActionResult General() { return View(); } public ActionResult HttpError404() { return View(); } public ActionResult HttpError500() { return View(); } } 

In Global.asax define the Application_Error method:

 protected void Application_Error(object sender, EventArgs e) { var exception = Server.GetLastError(); // TODO: Log the exception with your favorite logging framework Response.Clear(); var httpException = exception as HttpException; var routeData = new RouteData(); // Take the ErrorController routeData.Values.Add("controller", "error"); if (httpException == null) { // Use the General action for any unhandled error routeData.Values.Add("action", "general"); } else { switch (httpException.GetHttpCode()) { case 404: routeData.Values.Add("action", "httpError404"); break; case 500: routeData.Values.Add("action", "httpError500"); break; default: routeData.Values.Add("action", "general"); break; } } // Add the exception to route data so that the error controller // could use it with RouteData.Values["error"] routeData.Values.Add("error", exception); Server.ClearError(); IController errorController = new ErrorController(); errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData)); } 

Finally, throw the appropriate exceptions:

 public class HomeController: Controller { public ActionResult Index(int id) { var model = _repository.GetModel(id); if (model == null) { throw new HttpException(404, "Model not found with id = " + id); } return View(model); } } 
+8
source

All Articles