展示产品的网站 个人备案还是企业,推广网站的方法有,wordpress 轮播图插件,dede视频网站源码前言 在程序中#xff0c;经常需要处理比如 404#xff0c;500 #xff0c;502等错误#xff0c;如果直接返回错误的调用堆栈的具体信息#xff0c;显然大部分的用户看到是一脸懵逼的#xff0c;你应该需要给用户返回那些看得懂的界面。比如#xff0c;“当前页面不存在…前言 在程序中经常需要处理比如 404500 502等错误如果直接返回错误的调用堆栈的具体信息显然大部分的用户看到是一脸懵逼的你应该需要给用户返回那些看得懂的界面。比如“当前页面不存在了” 等等,本篇文章主要来讲讲.NET-Core 中异常处理以及如何自定义异常显示界面还有 如何定义自己的异常处理中间件。
.NET-Core 中的异常处理 让我们从下面这段代码讲起写过.Net-Core 的应该不陌生在 Startup 的 Configure 中定义异常处理的中间件。
if (env.IsDevelopment()){app.UseDeveloperExceptionPage();
}else{app.UseExceptionHandler(/error);
} 上面两种情况分别是一个是使用自带的异常处理另外一个是将错误异常的处理进行自己处理。两种情况如下所示
我在HomeController 中定义了一个Test Action如下所示仅仅为了演示并无实际意义
//Controllerpublic string Test(int id){ if(id 1){ return new System.NullReferenceException(Its not equals to 1, robert!);} return Bingo,Robert!;
}//Routingroutes.MapRoute(name: Error, template: error/,defaults: new { controller Home, action error }
); 使用 localhost:{port}/home/test/2 的结果像下面这样 对我localhost:{port}/home/test/1 这样呢在不同环境下是不一样的具体如下所示
UseDeveloperException UseExceptionHandler
这些呢就是比较平常的 .NET-Core 的处理方式。但是看不见StatusCode发现没有除了自定义的时候默认时是不提供Status Code 的。这时候就可以用到这个
UseStatusCodePages() 想要看源码的在这 StatusCodePagesExtension Source Code。
效果怎么样的呢如下所示 这是默认的处理方式看了源码我们知道UseStatusCodePages 有4个重载。还可以自己定义是不是感觉比前面的高级点下面是自定义具体就不演示了。
app.UseStatusCodePages(async context {context.HttpContext.Response.ContentType text/plain; await context.HttpContext.Response.WriteAsync($Whats the statusCode you got is {context.HttpContext.Response.StatusCode});
});app.UseStatusCodePages(text/plain,Whats the statusCode you got is {0}); 截止到上面为止基本的异常处理其实已经介绍的差不多了。但是总感觉那么普遍呢好像还不够特殊并且还满足不了我们的需求我们想要自定义错误的处理方式。比如我们想要遇到 404 时就显示 404 界面。
定义异常处理中间件 其实上面的自定义自己的异常处理时其实已经可以做到我们需要的情况了。我们在Error Action 中对HttpContext.Response.StatusCode 进行判断根据不同的StatusCode return 不同的View就可以了。但是为什么我们还需要定义特定处理的中间件主要目的是为了其他项目服务的如果你只有一个项目一个站点其实并没什么必要。但是如果有很多子站点时还是需要考虑的一下的。 模仿了一下 UseStatusCodePagesWithReExecute这个写了一个
using System;using System.Collections.Generic;using System.Text;using Microsoft.AspNetCore.Builder;using System.Globalization;using System.Threading.Tasks;using Microsoft.AspNetCore.Diagnostics;using Microsoft.AspNetCore.Http;using Microsoft.Extensions.Options;namespace MiddlewareDemo.CustomMiddleware{ /// summary/// Adds a StatusCodePages middleware to the pipeline. Specifies that the response body should be generated by /// re-executing the request pipeline using an alternate path. This path may contain a {0} placeholder of the status code./// /summary/// param nameapp/param/// param namepathFormat/param //因为直接 处理404 所以就不给参数啦。/// param namequeryFormat/param/// returns/returnspublic static class ErrorHandlerMiddlewareExtension{ public static IApplicationBuilder UseErrorHandler( this IApplicationBuilder app, string pathFormat /error, string queryFormat null) { if (app null){ throw new ArgumentNullException(nameof(app));} return app.UseStatusCodePages(async context { if (context.HttpContext.Response.StatusCode StatusCodes.Status404NotFound){ var newPath new PathString( string.Format(CultureInfo.InvariantCulture, pathFormat, context.HttpContext.Response.StatusCode)); var formatedQueryString queryFormat null ? null : string.Format(CultureInfo.InvariantCulture, queryFormat, context.HttpContext.Response.StatusCode); var newQueryString queryFormat null ? QueryString.Empty : new QueryString(formatedQueryString); var originalPath context.HttpContext.Request.Path; var originalQueryString context.HttpContext.Request.QueryString; // Store the original paths so the app can check it.context.HttpContext.Features.SetIStatusCodeReExecuteFeature(new StatusCodeReExecuteFeature(){OriginalPathBase context.HttpContext.Request.PathBase.Value,OriginalPath originalPath.Value,OriginalQueryString originalQueryString.HasValue ? originalQueryString.Value : null,});context.HttpContext.Request.Path newPath;context.HttpContext.Request.QueryString newQueryString; try{ await context.Next(context.HttpContext);} finally{context.HttpContext.Request.QueryString originalQueryString;context.HttpContext.Request.Path originalPath;context.HttpContext.Features.SetIStatusCodeReExecuteFeature(null);}}});}}
}
这样就会只处理404啦。
如下所示 最后分享一个 Re-execute vs Redirect 的一位大神的分析 其实在 StatusCodePagesExtensions中还有两个方法这两个方法也会比较实用主要是用来当遇到异常给你跳转到其他界面的。
//使用的话就像下面这样就可以啦app.UseStatusCodePagesWithReExecute(/error,?StatusCode{0});app.UseStatusCodePagesWithRedirects(/error);//具体可以用哪些参数呢可以去看源码这里就不多介绍了。
这两个的虽然都可以得到我们想要的结果但是过程差的有点多。先盗一下大神的两张图
第一张是 Redirect的 : 下面一张是 ReExecute 的 区别呢我用Chrome Developer Console 来给你们展示一下你们就明白啦。
这个是 redirect 的 很神奇吧它返回的是200 ok. 由于是 redirect 所以 地址 redirect 到了 localhost:52298/error 。看Network可知进行了两次请求第一次http://localhost:52298/home/testpage 时 返回302 Found. 我们知道这个是 404 的状态码被 middleware “抓到”后于是我们再次发起请求 http://localhost:52298/error这个请求当然返回的状态码是 200 啦。所以我们在下图的结果中可以看见。200 OK。 302 : The 302 (Found) status code is used where the redirection is temporary or generally subject to change, such that the client shouldnt store and reuse the redirect URL in the future 下面的是ReExecute 的 结语 如有陈述的不正确处请多多评论指正。
文章推荐及参考链接
Use statusCodeWithReExecute and pic referenceStatusCodePagesExtensions Source Code
相关文章
.NET Core 2.0 正式发布信息汇总.NET Standard 2.0 特性介绍和使用指南.NET Core 2.0 的dll实时更新、https、依赖包变更问题及解决.NET Core 2.0 特性介绍和使用指南Entity Framework Core 2.0 新特性体验 PHP under .NET Core.NET Core 2.0使用NLog升级项目到.NET Core 2.0在Linux上安装Docker并成功部署解决Visual Studio For Mac Restore失败的问题ASP.NET Core 2.0 特性介绍和使用指南.Net Core下通过Proxy 模式 使用 WCF.NET Core 2.0 开源Office组件 NPOIASP.NET Core - Razor页面之Handlers处理方法ASP.NET Core Razor页面 vs MVCRazor Page–Asp.Net Core 2.0新功能 Razor Page介绍ASP.Net Core 2.0中的Razor Page不是WebForm
原文地址http://www.cnblogs.com/xiyin/p/7507405.html .NET社区新闻深度好文微信中搜索dotNET跨平台或扫描二维码关注