当前位置: 移动技术网 > IT编程>开发语言>.net > (7)处理ASP.NET Core 中的错误

(7)处理ASP.NET Core 中的错误

2019年05月31日  | 移动技术网IT编程  | 我要评论

全国白酒招商,王乐全被抓了,tonewin

1.前言

asp.net core处理错误环境区分为两种:开发环境和非开发环境。
开发环境:开发人员异常页。
非开发环境:异常处理程序页、状态代码页。
在startup.configure方法里面我们会看到如下代码:

public void configure(iapplicationbuilder app, ihostingenvironment env)
{
    if (env.isdevelopment())
    {
       //开发环境
    } 
    else
    {
       //非开发环境
    }
}

env.isdevelopment()是判断应用程序运行是在开发环境还是非开发环境,具体配置在properties/launchsettings.json,找到aspnetcore_environment属性,默认值是开发环境(development),具体环境配置知识点后面我们再来学习下。

2.开发人员异常页

向startup.configure方法添加代码,以当应用在开发环境中运行时启用此页:

if (env.isdevelopment())
{
    app.usedeveloperexceptionpage();
}

开发人员异常页仅当应用程序在开发环境中运行时才会启用,而且调用usedeveloperexceptionpage要配置于任何要捕获其异常的中间件前面。
该页包括关于异常和请求的以下信息:
●堆栈跟踪
●查询字符串参数(如果有)
●cookie(如果有)
●request header

3.异常处理程序页

在下面的示例中,useexceptionhandler 在非开发环境中添加异常处理中间件:

if (env.isdevelopment())
{
    app.usedeveloperexceptionpage();
}
else
{
    app.useexceptionhandler("/error");
    app.usehsts();
}

razor pages应用模板提供“页面”文件夹中的error页(.cshtml)和pagemodel类(errormodel)。 对于mvc应用,项目模板包括error操作方法和error视图。操作方法如下:

[allowanonymous]
[responsecache(duration = 0, location = responsecachelocation.none, nostore = true)]
public iactionresult error()
{
    return view(new errorviewmodel { requestid = activity.current?.id ?? httpcontext.traceidentifier });
}

不要使用http方法属性(如httpget)修饰错误处理程序操作方法,因为会阻止某些请求访问的方法。同时最好允许匿名访问方法,以便未经身份验证的用户能够接收错误视图。
useexceptionhandler中间还可以使用lambda进行异常处理:

if (env.isdevelopment())
{
    app.usedeveloperexceptionpage();
}
else
{
   app.useexceptionhandler(errorapp =>
   {
        errorapp.run(async context =>
        {
            context.response.statuscode = 500;
            context.response.contenttype = "text/html";
            await context.response.writeasync("<html lang=\"en\"><body>\r\n");
            await context.response.writeasync("error!<br><br>\r\n");
            var exceptionhandlerpathfeature = 
                context.features.get<iexceptionhandlerpathfeature>();
            // use exceptionhandlerpathfeature to process the exception (for example, 
            // logging), but do not expose sensitive error information directly to 
            // the client.
            if (exceptionhandlerpathfeature?.error is filenotfoundexception)
            {
                await context.response.writeasync("file error thrown!<br><br>\r\n");
            }
            await context.response.writeasync("<a href=\"/\">home</a><br>\r\n");
            await context.response.writeasync("</body></html>\r\n");
            await context.response.writeasync(new string(' ', 512)); // ie padding
        });
    });
app.usehsts();
}

4.状态代码页

一般情况下,asp.net core应用程序不会为http状态代码(如“404-未找到”)提供状态代码页的。但若要提供状态代码页,可以使用状态代码页中间件。

4.1 usestatuscodepages中间件

若要启用常见错误状态代码的默认纯文本处理程序,请在startup.configure方法中调用 usestatuscodepages:

app.usestatuscodepages();

而这里有一点要注意的是,调用usestatuscodepages中间件要在例如静态文件中间件和 mvc中间件等中间件前面调用:

app.usestatuscodepages();
app.usestaticfiles();
app.usemvc(routes =>
{
    routes.maproute(
        name: "default",
        template: "{controller=home}/{action=index}/{id?}");
});

下面通过运行应用程序在浏览器地址栏上输入一个不存在地址看看配置该中间件后的效果:

很显然当我们输入一个不存在地址之后就会打开一个处理错误的状态代码页。
usestatuscodepages中间件还有两种重载使用方法,具体运行效果就不一一截图了,大家自行测试。
●包含格式字符串的 usestatuscodepages:

app.usestatuscodepages("text/plain", "status code page, status code: {0}");

●包含lambda的usestatuscodepages:

app.usestatuscodepages(async context =>
{
    context.httpcontext.response.contenttype = "text/plain";
    await context.httpcontext.response.writeasync(
        "status code page, status code: " +
        context.httpcontext.response.statuscode);
});

4.2 usestatuscodepageswithredirect中间件

●向客户端发送“302 - 已找到”状态代码。
●将客户端重定向到url模板中的位置。
下面我们在startup.configure方法中调用usestatuscodepageswithredirect:

app.usestatuscodepageswithredirects("/error/{0}");

运行应用程序在浏览器上输入不存在地址https://localhost:44353/1看看配置该中间件后的效果,你会发觉当我们输入上述地址后会跳转到https://localhost:44353/error/404链接去了,并显示:

这就说明白当我们输入一个不存在地址之后会重定向中间件设置的地址页面去了。

参考文献:
处理 asp.net core 中的错误

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网