10
How to display a friendlier page when an error occurs in my Asp.net mvc application (not that yellow page)?
10
How to display a friendlier page when an error occurs in my Asp.net mvc application (not that yellow page)?
9
There is a special view for these cases, the Shared/Error.cshtml
(has to be this name).
Just turn on the customErrors
of its application in Web.config:
<system.web>
<customErrors mode="On" />
</system.web>
If you want to display error details, such as name of the action, controller name or the exception, you can configure your view to receive a model of the type Handleerrorinfo.
The only problem is that, unfortunately, this solution does not meet 404 errors (page not found). Asp.net mvc does not support this type of error so easily.
To treat it you will need a write own action for it (a proper URL). Example, for the URL ~/erros/nao-encontrado
:
<customErrors mode="On">
<error statusCode="404" redirect="~/erros/nao-encontrado" />
</customErrors>
In this case you are given the original URL via query string:
http://localhost/erros/nao-encontrado?aspxerrorpath=/administracao/algum-cadastro
2
On my website I modified Global.asax.Cs and includes
protected void Application_Error(object sender, EventArgs e)
{
var app = (MvcApplication)sender;
var context = app.Context;
var ex = app.Server.GetLastError();
context.Response.Clear();
context.ClearError();
var httpException = ex as HttpException;
var routeData = new RouteData();
routeData.Values["controller"] = "errors";
routeData.Values["exception"] = ex;
routeData.Values["action"] = "http500";
if (httpException != null)
{
switch (httpException.GetHttpCode())
{
case 404:
routeData.Values["action"] = "http404";
break;
case 500:
routeData.Values["action"] = "http500";
break;
}
}
IController controller = new ErrorsController();
controller.Execute(new RequestContext(new HttpContextWrapper(context), routeData));
}
And I created a Controller
to manage the errors
public class ErrorsController : Controller
{
public ActionResult Http404(Exception exception)
{
Response.StatusCode = 404;
Response.ContentType = "text/html";
return View(exception);
}
public ActionResult Http500(Exception exception)
{
Response.StatusCode = 500;
Response.ContentType = "text/html";
return View(exception);
}
}
This way if you access a non-existent page you will be redirected to Action Http404
controller’s Errors
.
If you are trying to access an item (e.g., a product) and it does not exist, you can launch a 404 error.
Example URL: /produtos/detalhes/10
Produto x = db.GetProduto(10);
if (x == null)
throw new HttpException(404, "Not Found");
0
You can create an Error controler by returning to the Error View according to the error generated
public class ErrorController : Controller
{
//Erro 500 Servidor
public ActionResult Index()
{
ViewBag.AlertaErro = "Ocorreu um Erro :(";
ViewBag.MensagemErro = "Tente novamente ou " +
"contate um Administrador";
return View("Error");
}
//Error 404
public ActionResult NotFound()
{
ViewBag.AlertaErro = "Ocorreu um Erro :(";
ViewBag.MensagemErro = "Não existe uma página para a URL informada";
return View("Error");
}
//Erro 401 permissão de execução
public ActionResult AccessDenied()
{
//ViewBag.AlertaErro = "Acesso Negado :(";
//ViewBag.MensagemErro = "Você não tem permissão para executar isso";
return PartialView("Error403");
}
Now in Webconfig, you insert this code:
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="500" />
<remove statusCode="404" />
<remove statusCode="403" />
<error statusCode="500" responseMode="ExecuteURL" path="/Error/Index" />
<error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound" />
<error statusCode="403" responseMode="ExecuteURL" path="/Error/AccessDenied" />
</httpErrors>
It is very easy to understand, in practice it replaces the standard error mensganes and will use the ones you configured in Controler
Browser other questions tagged c# asp.net-mvc error-page
You are not signed in. Login or sign up in order to post.