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

2020-02-23 08:38发布

问题:

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 =>
            {

回答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



回答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();
    }