ASP.Net 5 MVC 6, how to use shared Error.cshtml as default error response
To Handle 404s and Internal Errors you need to modify the error signature.
I've explicitly commented out the debugging error handlers in my Dev environment in the Startup.cs. If you don't want to do this use the environment variable in the project.
Add this to the Startup.cs
if (env.IsDevelopment())
{
// Uncomment when done testing error handling
//app.UseBrowserLink();
//app.UseDeveloperExceptionPage();
//app.UseDatabaseErrorPage();
// Comment when done testing error handling
app.UseExceptionHandler("/Home/Error");
}
else
{
app.UseExceptionHandler("/Home/Error");
//For more details on creating database during deployment see http://go.microsoft.com/fwlink/?LinkID=615859
try
{
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
.CreateScope())
{
serviceScope.ServiceProvider.GetService<ApplicationDbContext>()
.Database.Migrate();
}
}
catch { }
}
// Lines Skipped For Brevity ....
// Add this line above app.Mvc in Startup.cs to Handle 404s etc
app.UseStatusCodePagesWithReExecute("/Home/Error/{0}");
Add this to the HomeController.cs
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Diagnostics;
using Microsoft.AspNet.Http.Features;
// id = Http Status Error
public IActionResult Error(String id)
{
var feature = HttpContext.Features.Get<IExceptionHandlerFeature>();
var undhandledException = feature?.Error;
var iisError = id;
return View();
}
in Startup class:
app.UseExceptionHandler("/Home/Error");
in HomeController:
public IActionResult Error()
{
var feature = this.HttpContext.Features.Get<IExceptionHandlerFeature>();
return View("~/Views/Shared/Error.cshtml", feature?.Error);
}
the Error.cshtml view can look like :
@model Exception
@{
ViewBag.Title = "Oops!";
}
<h1 class="text-danger">Oops! an error occurs</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>
@if (Model != null)
{
@Html.ValueFor(model => model.Message)
}
this code is part of project available on GitHub