如何在MVC启动中使用UseExceptionHandler而不重定向用户? [英] How to use UseExceptionHandler in the mvc startup without redirecting the user?

查看:43
本文介绍了如何在MVC启动中使用UseExceptionHandler而不重定向用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET Core 2.1 MVC应用程序,当出现异常时,我试图返回一个单独的html视图.这样做的原因是,如果有错误,我们不希望Google为我们的SEO注册到错误页面的重定向(我省略了开发设置以清除问题).

我们的创业公司包含以下内容:

  app.UseExceptionHandler("/Error/500");//由于某些中间件,这导致了重定向.app.UseStatusCodePagesWithReExecute("/error/{0}"); 

但是我们要防止重定向,因此我们需要更改UseExceptionHandler.我尝试使用以下

I have a ASP.NET Core 2.1 MVC application, and I'm trying to return a separate html view when an exception occurs. The reason for this is that if there are errors, we don't want google to register the redirects to the error page for our SEO (I've omitted development settings to clear things up).

Our startup contained this:

app.UseExceptionHandler("/Error/500"); // this caused a redirect because some of our middleware.
app.UseStatusCodePagesWithReExecute("/error/{0}"); 

But we want to prevent a redirect, so we need to change the UseExceptionHandler. I've tried to use the answer from this question like below:

app.UseExceptionHandler(
            options =>
            {
                options.Run(
                    async context =>
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                        context.Response.ContentType = "text/html";
                        await context.Response.WriteAsync("sumtin wrong").ConfigureAwait(false);

                    });
            });

But this gives a very ugly page without any styling. Another solution we've tried to use is creating an error handling middle ware, but there we run into the same problem there where we can't add a view.

How can I return a styled view in case of an exception, without redirecting the user?

EDIT: the UseExceptionHandler doesn't cause a redirect, it was caused by a bug in some of our middleware.

解决方案

How can I return a styled view in case of an exception, without redirecting the user?

You're almost there. You could rewrite(instead of redirect) the path, and then serve a HTML according to current path.

Let's say you have a well-styled sth-wrong.html page in your wwwroot/ folder. Change the code as below:

app.UseExceptionHandler(appBuilder=>
{
    // override the current Path
    appBuilder.Use(async (ctx, next)=>{
        ctx.Request.Path = "/sth-wrong.html";
        await next();
    });
    // let the staticFiles middleware to serve the sth-wrong.html
    appBuilder.UseStaticFiles();
});


[Edit] :

Is there anyway where I can make use of my main page layout?

Yes. But because a page layout is a View Feature that belongs to MVC, you can enable another MVC branch here

  1. First create a Controllers/ErrorController.cs file :

    public class ErrorController: Controller
    {
        public IActionResult Index() => View();
    }
    

    and a related Views/Error/Index.cshtml file:

    Ouch....Something bad happens........
    

  2. Add a MVC branch in middleware pipeline:

    app.UseExceptionHandler(appBuilder=>
    {
        appBuilder.Use(async (ctx, next)=>{
            ctx.Request.Path = "/Error/Index";
            await next();
        });
        appBuilder.UseMvc(routes =>{
            routes.MapRoute(
                name: "sth-wrong",
                template: "{controller=Error}/{action=Index}");
        });
    });
    

Demo:

这篇关于如何在MVC启动中使用UseExceptionHandler而不重定向用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆