ASP.Net 5 MVC 6, how to use shared Error.cshtml as default error response

17,314

Solution 1

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

Solution 2

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();
    }
Share:
17,314
agua from mars
Author by

agua from mars

I'm good at developing software with C#, TypeScript and Javascript. I'm good at integrating tools in a CI/CD chain. I'm ASP.NET Core Identity and Blazor projects contributor. If you sponsor me, feel free to contact me on gitter More about me

Updated on June 21, 2022

Comments

  • agua from mars
    agua from mars almost 2 years

    ASP.Net 5 MVC 6, how to use shared Error.cshtml as default error response

    when using Microsoft.AspNet.Diagnostics UseExceptionHandler middleware with a razor view

    If you look at the sample code at https://github.com/aspnet/Diagnostics/tree/dev/samples/ExceptionHandlerSample/Startup.cs explaning how to use Microsoft.AspNet.Diagnostics ErrorHandler middleware for ASP.Net 5,a comment say:

    // Normally you'd use MVC or similar to render a nice page.

    Ok, but how to do that ?

    public class Startup
    {
        public void Configure(IApplicationBuilder app)
        {
            // Configure the error handler to show an error page.
            app.UseExceptionHandler(errorApp =>
            {
                // Normally you'd use MVC or similar to render a nice page.
                errorApp.Run(async context =>
                {
    
  • Samurai Ken
    Samurai Ken almost 9 years
    Unfortunately this does not seem to actually work - at least not using IIS Express with VS2015. I still get the default error message. "HTTP Error 404.0 - Not Found The resource you are looking for has been removed, had its name changed, or is temporarily unavailable."
  • agua from mars
    agua from mars almost 9 years
    I didn't retest it with beta4
  • agua from mars
    agua from mars almost 9 years
    @Soulhuntre Error handler handles uncactched exception, not 404, you need to create your own middleware or use iss settings to customize 404 page
  • Serj Sagan
    Serj Sagan over 8 years
    Great! app.UseStatusCodePagesWithReExecute("/Home/Error/{0}"); is what I needed
  • Barbaros Alp
    Barbaros Alp about 8 years
    Thank you so much Chris, you made my day!
  • OrangeKing89
    OrangeKing89 over 7 years
    I have been trying to find how to reference the error for a while now. Thanks! (this.HttpContext.Features.Get<IExceptionHandlerFeature>();)
  • agua from mars
    agua from mars over 3 years
    The question is about MVC 6 not 5. and your response is per action, not the default behavior