Asp.net Core WebApi 全局异常类
2016-11-26 21:41
936 查看
通过全局异常类,所有程序中遇到的错误都会被拦截,并友好的返回结果。
1、自定义一个全局异常处理类中间件
返回值默认格式化成自定义类ResultMsg,可根据自己的项目需求,返回自定义实体
同时会根据客户端需要的格式,自动转换为xml或者json
2、configure注册
3、收工,所有异常均可以处理了
1、自定义一个全局异常处理类中间件
using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Threading.Tasks; using System.Xml.Serialization; using UFX.Mall.EntityModel; using UFX.Tools; namespace UFX.Mall.WebApi { public class ExceptionHandlerMiddleWare { private readonly RequestDelegate next; public ExceptionHandlerMiddleWare(RequestDelegate next) { this.next = next; } public async Task Invoke(HttpContext context) { try { await next(context); } catch (Exception ex) { await HandleExceptionAsync(context, ex); } } private static async Task HandleExceptionAsync(HttpContext context, Exception exception) { if (exception == null) return; await WriteExceptionAsync(context, exception).ConfigureAwait(false); } private static async Task WriteExceptionAsync(HttpContext context, Exception exception) { //记录日志 LogHelper.Error(exception.GetBaseException().ToString()); //返回友好的提示 var response = context.Response; //状态码 if (exception is UnauthorizedAccessException) response.StatusCode = (int)HttpStatusCode.Unauthorized; else if (exception is Exception) response.StatusCode = (int)HttpStatusCode.BadRequest; response.ContentType = context.Request.Headers["Accept"]; if (response.ContentType.ToLower() == "application/xml") { await response.WriteAsync(Object2XmlString(ResultMsg.Failure(exception.GetBaseException().Message))).ConfigureAwait(false); } else { response.ContentType = "application/json"; await response.WriteAsync(JsonConvert.SerializeObject(ResultMsg.Failure(exception.GetBaseException().Message))).ConfigureAwait(false); } } /// <summary> /// 对象转为Xml /// </summary> /// <param name="o"></param> /// <returns></returns> private static string Object2XmlString(object o) { StringWriter sw = new StringWriter(); try { XmlSerializer serializer = new XmlSerializer(o.GetType()); serializer.Serialize(sw, o); } catch { //Handle Exception Code } finally { sw.Dispose(); } return sw.ToString(); } } }
返回值默认格式化成自定义类ResultMsg,可根据自己的项目需求,返回自定义实体
同时会根据客户端需要的格式,自动转换为xml或者json
2、configure注册
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); //配置NLog loggerFactory.AddNLog(); env.ConfigureNLog("nlog.config"); app.UseApplicationInsightsRequestTelemetry(); app.UseApplicationInsightsExceptionTelemetry(); //异常处理中间件 app.UseMiddleware(typeof(ExceptionHandlerMiddleWare)); app.UseMvc(); ; }
3、收工,所有异常均可以处理了
相关文章推荐
- C#实现多级子目录Zip压缩解压实例 NET4.6下的UTC时间转换 [译]ASP.NET Core Web API 中使用Oracle数据库和Dapper看这篇就够了 asp.Net Core免费开源分布式异常日志收集框架Exceptionless安装配置以及简单使用图文教程 asp.net core异步进行新增操作并且需要判断某些字段是否重复的三种解决方案 .NET Core开发日志
- asp.net core webapi项目配置全局路由的方法示例
- asp.net core webapi项目配置全局路由
- asp.net core WebAPI实现CRUD
- asp.net core webapi 使用swagger
- 支持多个版本的ASP.NET Core Web API
- ASP.NET Core WebApi 返回统一格式参数
- ASP.NET Core Web API Cassandra CRUD 操作
- ASP.NET Core Web APi获取原始请求内容
- ASP.NET Core Web API下事件驱动型架构的实现(二):事件处理器中对象生命周期的管理
- Asp.net Core WebApi 支持json/xml格式的数据返回
- Using MongoDB with Web API and ASP.NET Core
- [译]ASP.NET Core Web API 中使用Oracle数据库和Dapper看这篇就够了
- 在ASP.NET Core Web API中为RESTful服务增加对HAL的支持
- asp.net core webapi swagger 使用二
- 如何在ASP.NET Core Web API测试中使用Postman
- Asp.net core WebApi 使用Swagger生成帮助页实例
- Gitlab CI 自动部署 asp.net core web api 到Docker容器
- 在docker中运行ASP.NET Core Web API应用程序(附AWS Windows Server 2016 widt Container实战案例)
- asp.net core webapi实现jwt授权认证