From 1b5155aeaaa9ff1cd3bea18fa22eebf670459b88 Mon Sep 17 00:00:00 2001 From: HTR Date: Mon, 2 Jul 2018 18:15:35 +0800 Subject: [PATCH] fix vali middleware --- COMCMS.Web/Common/JsonExtension.cs | 16 +++ .../Common/WebAPIHandleErrorAttribute.cs | 4 +- .../Controllers/api/APIBaseController.cs | 116 ------------------ COMCMS.Web/Controllers/api/IndexController.cs | 46 +++---- .../Controllers/api/PaymentController.cs | 62 +++++----- COMCMS.Web/Controllers/api/ReJson.cs | 62 ++++++++++ COMCMS.Web/Controllers/api/UserController.cs | 85 +++++-------- .../ResultExceptionHandler.cs | 23 ++++ COMCMS.Web/Filter/CheckFilter.cs | 94 ++++++++++++++ COMCMS.Web/Startup.cs | 4 + Lib.Core/Lib.Core.csproj | 11 ++ .../ExceptionHandlingMiddleware.cs | 33 +++++ .../Extension/MiddlewareExtension.cs | 17 +++ .../MiddlewareExtension/IExceptionHandler.cs | 11 ++ 14 files changed, 358 insertions(+), 226 deletions(-) create mode 100644 COMCMS.Web/Common/JsonExtension.cs delete mode 100644 COMCMS.Web/Controllers/api/APIBaseController.cs create mode 100644 COMCMS.Web/Controllers/api/ReJson.cs create mode 100644 COMCMS.Web/ExceptionHandler/ResultExceptionHandler.cs create mode 100644 COMCMS.Web/Filter/CheckFilter.cs create mode 100644 Lib.Core/Lib.Core.csproj create mode 100644 Lib.Core/MiddlewareExtension/ExceptionHandlingMiddleware.cs create mode 100644 Lib.Core/MiddlewareExtension/Extension/MiddlewareExtension.cs create mode 100644 Lib.Core/MiddlewareExtension/IExceptionHandler.cs diff --git a/COMCMS.Web/Common/JsonExtension.cs b/COMCMS.Web/Common/JsonExtension.cs new file mode 100644 index 0000000..b7a76a8 --- /dev/null +++ b/COMCMS.Web/Common/JsonExtension.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Newtonsoft.Json; + +namespace COMCMS.Web.Common +{ + public static class JsonExtension + { + public static string ToJson(this TEntity entity) where TEntity : class + { + return JsonConvert.SerializeObject(entity); + } + } +} diff --git a/COMCMS.Web/Common/WebAPIHandleErrorAttribute.cs b/COMCMS.Web/Common/WebAPIHandleErrorAttribute.cs index 87c3f42..a8890a8 100644 --- a/COMCMS.Web/Common/WebAPIHandleErrorAttribute.cs +++ b/COMCMS.Web/Common/WebAPIHandleErrorAttribute.cs @@ -16,9 +16,7 @@ namespace COMCMS.Web.Common { context.HttpContext.Request.ContentType = "application/json"; context.HttpContext.Request.Headers["Accept"] = "application/json"; - ReJSON model = new ReJSON(); - model.code = 5001; - model.message = "执行错误:"+ context.Exception.Message; + ReJSON model = new ReJSON(5001, "执行错误:" + context.Exception.Message); context.Result = new JsonResult(model); base.OnException(context); } diff --git a/COMCMS.Web/Controllers/api/APIBaseController.cs b/COMCMS.Web/Controllers/api/APIBaseController.cs deleted file mode 100644 index 3c019c7..0000000 --- a/COMCMS.Web/Controllers/api/APIBaseController.cs +++ /dev/null @@ -1,116 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using COMCMS.Common; -using COMCMS.Web.Common; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using NewLife.Log; - -namespace COMCMS.Web.Controllers.api -{ - [Produces("application/json")] - [Route("api/[controller]/[action]")] - [WebAPIHandleError] - public class APIBaseController : Controller - { - public APIBaseController() - { - string url = MyHttpContext.Current.Request.Path; - string querystring = MyHttpContext.Current.Request.QueryString.ToString(); - XTrace.WriteLine($"访问API:{url}?{querystring}"); - } - #region 通用信息 - public ReJSON reJson = new ReJSON() { code = 40000 }; - #endregion - - #region 验证签名 - public bool CheckSignature(SortedDictionary pars, string signature) - { - if (!MySign.CheckSign(pars, signature)) - { - reJson.code = 40004; - reJson.message = "signature 错误!"; - return false; - } - //判断是否超时 - string timeStamp = pars["timeStamp"]; - //判断时间有效性 - DateTime postTime = Utils.StampToDateTime(timeStamp); - if (postTime < DateTime.Now.AddSeconds(-120))//30秒有效期 - { - reJson.code = 40004; - reJson.message = "数据请求超时!"; - reJson.isReload = 1; - return false; - } - return true; - } - - #endregion - - #region 自动验证QueryString 的签名 - /// - /// 自动验证QueryString 的签名 - /// - /// - public bool AutoCheckQueryStringSignature() - { - var queryStrings = Request.Query; - List keys = new List(); - //string[] keys = HttpContext.Current.Request.QueryString.AllKeys; - if (queryStrings == null) - { - return false; - } - foreach (var item in queryStrings.Keys) - { - keys.Add(item); - } - SortedDictionary pars = new SortedDictionary(); - string signature = ""; - foreach (var k in keys) - { - if (k != "signature") - { - string v = Request.Query[k]; - pars.Add(k, v); - } - else - { - signature = Request.Query[k]; - } - } - //没有签名返回错误 - if (string.IsNullOrEmpty(signature)) - return false; - return CheckSignature(pars, signature); - } - #endregion - } - - #region 通用返回信息 - public class ReJSON - { - /// - /// 返回代码 0 为正确 - /// - public int code { get; set; } = 40000; - - /// - /// 提示语 - /// - public string message { get; set; } - /// - /// 是否重新加载 - /// - public int isReload { get; set; } = 0; - - /// - /// 数据详情 object - /// - public object detail { get; set; } - } - #endregion -} \ No newline at end of file diff --git a/COMCMS.Web/Controllers/api/IndexController.cs b/COMCMS.Web/Controllers/api/IndexController.cs index b690b6c..56f975a 100644 --- a/COMCMS.Web/Controllers/api/IndexController.cs +++ b/COMCMS.Web/Controllers/api/IndexController.cs @@ -5,6 +5,7 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using COMCMS.Common; using COMCMS.Core; +using COMCMS.Web.Filter; using XCode; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 @@ -12,7 +13,7 @@ using XCode; namespace COMCMS.Web.Controllers.api { - public class IndexController : APIBaseController + public class IndexController : Controller { // GET: api/ [HttpGet] @@ -22,7 +23,7 @@ namespace COMCMS.Web.Controllers.api return cfg; } - #region 测试验签 + //#region 测试验签 /// /// 测试验签 /// @@ -31,31 +32,22 @@ namespace COMCMS.Web.Controllers.api /// /// /// - [HttpGet] - public object CheckSign(string id, string random = "", string timeStamp = "", string signature = "") - { - if (!AutoCheckQueryStringSignature()) - { - reJson.message = "验签失败!"; - return reJson; - } - else - { - reJson.code = 0; - reJson.message = "验签成功!"; - return reJson; - } - } - #endregion + //[HttpGet] + //[CheckFilter] + //public ReJSON CheckSign(string id, string random = "", string timeStamp = "", string signature = "") + //{ + // return new ReJSON("验签成功!"); + //} + //#endregion - #region 测试出错 - [HttpGet] - public object GetTest() - { - int a = 1,b=0; - var c = a / b; - return reJson; - } - #endregion + //#region 测试出错 + //[HttpGet] + //public object GetTest() + //{ + // int a = 1,b=0; + // var c = a / b; + // return reJson; + //} + //#endregion } } diff --git a/COMCMS.Web/Controllers/api/PaymentController.cs b/COMCMS.Web/Controllers/api/PaymentController.cs index ef79045..f649e3c 100644 --- a/COMCMS.Web/Controllers/api/PaymentController.cs +++ b/COMCMS.Web/Controllers/api/PaymentController.cs @@ -5,6 +5,7 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using COMCMS.Common; using COMCMS.Core; +using COMCMS.Web.Filter; using XCode; using NewLife.Log; using Senparc.Weixin.MP; @@ -16,45 +17,46 @@ namespace COMCMS.Web.Controllers.api /// /// 支付API /// - public class PaymentController : APIBaseController + public class PaymentController : Controller { #region 微信小程序订单支付 [HttpGet] - public object DoPayOrder(string ordernum, string random = "", string timeStamp = "", string signature = "") + [CheckFilter] + public ReJson DoPayOrder(string ordernum, string random = "", string timeStamp = "", string signature = "") { - if (!AutoCheckQueryStringSignature()) - { - return reJson; - } - //获取订单 Order entity = Order.Find(Order._.OrderNum == ordernum); if (entity == null) { - reJson.code = 40000; - reJson.message = "系统找不到本订单!"; - return reJson; + //reJson.code = 40000; + //reJson.message = "系统找不到本订单!"; + //return reJson; + + return new ReJson(40000, "系统找不到本订单!"); } //判断订单状态 if (entity.OrderStatus == Utils.OrdersState[3]) { - reJson.code = 40000; - reJson.message = "已完成订单不允许支付!"; - return reJson; + //reJson.code = 40000; + //reJson.message = "已完成订单不允许支付!"; + //return reJson; + return new ReJson(40000, "已完成订单不允许支付!"); } if (entity.PaymentStatus != Utils.PaymentState[0]) { - reJson.code = 40000; - reJson.message = "当前订单支付状态不允许支付!"; - return reJson; + //reJson.code = 40000; + //reJson.message = "当前订单支付状态不允许支付!"; + //return reJson; + return new ReJson(40000, "当前订单支付状态不允许支付!"); } //获取用户并判断是否是已经注册用户 Member my = Member.FindById(entity.UId); if (my == null || string.IsNullOrEmpty(my.WeixinAppOpenId)) { - reJson.code = 40000; - reJson.message = "用户状态错误,无法使用本功能!"; - return reJson; + //reJson.code = 40000; + //reJson.message = "用户状态错误,无法使用本功能!"; + //return reJson; + return new ReJson(40000, "用户状态错误,无法使用本功能!"); } //开始生成支付订单 OnlinePayOrder model = new OnlinePayOrder(); @@ -112,9 +114,10 @@ namespace COMCMS.Web.Controllers.api if (result.return_code == "FAIL") { - reJson.code = 40005; - reJson.message = result.return_msg; - return reJson; + //reJson.code = 40005; + //reJson.message = result.return_msg; + //return reJson; + return new ReJson(40005, result.return_msg); } string nativeReqSign = res.CreateMd5Sign("key", TenPayV3Info.Key); //https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=3 @@ -125,10 +128,11 @@ namespace COMCMS.Web.Controllers.api dynamic detail = new { timeStamp = rtimeStamp, nonceStr = nonceStr, package = package, signType = "MD5", paySign = paySign }; - reJson.code = 0; - reJson.message = "下单成功!"; - reJson.detail = detail; - return reJson; + //reJson.code = 0; + //reJson.message = "下单成功!"; + //reJson.detail = detail; + //return reJson; + return new ReJson(40000, "下单成功!", detail); } catch (Exception ex) { @@ -136,9 +140,9 @@ namespace COMCMS.Web.Controllers.api res.SetParameter("return_msg", "统一下单失败"); XTrace.WriteLine($"统一下单失败:{ex.Message}"); - reJson.code = 40005; - reJson.message = "统一下单失败,请联系管理员!"; - return reJson; + //reJson.code = 40005; + //reJson.message = "统一下单失败,请联系管理员!"; + return new ReJson(40005, "统一下单失败,请联系管理员!"); } } #endregion diff --git a/COMCMS.Web/Controllers/api/ReJson.cs b/COMCMS.Web/Controllers/api/ReJson.cs new file mode 100644 index 0000000..2e582c4 --- /dev/null +++ b/COMCMS.Web/Controllers/api/ReJson.cs @@ -0,0 +1,62 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using COMCMS.Common; +using COMCMS.Web.Common; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using NewLife.Log; + +namespace COMCMS.Web.Controllers.api +{ + #region 通用返回信息 + public class ReJson + { + public ReJson(string message) + { + this.message = message; + code = 0; + } + + public ReJson(int code, string message) + { + this.code = code; + this.message = message; + } + + public ReJson(int code, string message, int isReload) + { + this.code = code; + this.message = message; + this.isReload = isReload; + } + + public ReJson(int code, string message, object detail) + { + this.code = code; + this.message = message; + this.detail = detail; + } + + /// + /// 返回代码 0 为正确 + /// + public int code { get; set; } = 40000; + + /// + /// 提示语 + /// + public string message { get; set; } + /// + /// 是否重新加载 + /// + public int isReload { get; set; } = 0; + + /// + /// 数据详情 object + /// + public object detail { get; set; } + } + #endregion +} \ No newline at end of file diff --git a/COMCMS.Web/Controllers/api/UserController.cs b/COMCMS.Web/Controllers/api/UserController.cs index 2d24558..4d5bce1 100644 --- a/COMCMS.Web/Controllers/api/UserController.cs +++ b/COMCMS.Web/Controllers/api/UserController.cs @@ -9,6 +9,7 @@ using COMCMS.Core; using COMCMS.Core.Models; using XCode; using System.Web; +using COMCMS.Web.Filter; using NewLife.Log; using static COMCMS.Web.Models.APIModels; using Newtonsoft.Json; @@ -16,7 +17,7 @@ using Newtonsoft.Json.Linq; namespace COMCMS.Web.Controllers.api { - public class UserController : APIBaseController + public class UserController : Controller { #region 用户登录 /// @@ -28,16 +29,12 @@ namespace COMCMS.Web.Controllers.api /// /// [HttpGet] - public object UserLogin(string code, string random = "", string timeStamp = "", string signature = "") + [CheckFilter] + public ReJson UserLogin(string code, string random = "", string timeStamp = "", string signature = "") { - if (!AutoCheckQueryStringSignature()) - { - return reJson; - } if (string.IsNullOrEmpty(code)) { - reJson.message = "请允许用户授权信息!"; - return reJson; + return new ReJson("请允许用户授权信息!"); } Config cfg = Config.GetSystemConfig(); string appid = cfg.WXAppId;// ConfigurationManager.AppSettings["wxappAppId"]; @@ -51,8 +48,7 @@ namespace COMCMS.Web.Controllers.api if (!string.IsNullOrEmpty(json.errcode)) { XTrace.WriteLine("微信服务器回调失败:" + json.errcode); - reJson.message = "注册失败,请联系管理员。" + json.errcode; - return reJson; + return new ReJson("注册失败,请联系管理员。" + json.errcode); } if (Member.FindCount(Member._.WeixinAppOpenId == json.openid, null, null, 0, 0) > 0) { @@ -60,9 +56,9 @@ namespace COMCMS.Web.Controllers.api if (my == null) { XTrace.WriteLine("登录成功,但是系统找不到用户:"); - reJson.code = 5003; - reJson.message = "系统找不到本用户!"; - return reJson; + //reJson.code = 5003; + //reJson.message = "系统找不到本用户!"; + return new ReJson(5003, "系统找不到本用户!"); } //如果存在,则返回个人信息 @@ -90,10 +86,10 @@ namespace COMCMS.Web.Controllers.api } string nickName = my.Nickname; if (!string.IsNullOrEmpty(nickName)) nickName = HttpUtility.UrlDecode(nickName); - reJson.code = 0; - reJson.message = "登录成功!"; - reJson.detail = new { sessionkey = mysessionkey, username = nickName, userimg = my.UserImg }; - return reJson; + //reJson.code = 0; + //reJson.message = "登录成功!"; + var detail = new { sessionkey = mysessionkey, username = nickName, userimg = my.UserImg }; + return new ReJson(0, "登录成功!", detail); //return new { code = 0, message = "登录成功", sessionkey = mysessionkey, username = nickName, userimg = my.UserImg }; } else @@ -129,10 +125,10 @@ namespace COMCMS.Web.Controllers.api entity.AddTime = DateTime.Now; entity.UId = m.Id; entity.Insert(); - reJson.code = 0; - reJson.message = "注册成功!"; - reJson.detail = new { sessionkey = entity.Key, username = "", userimg = m.UserImg }; - return reJson; + //reJson.code = 0; + //reJson.message = "注册成功!"; + var detail = new { sessionkey = entity.Key, username = "", userimg = m.UserImg }; + return new ReJson(0, "注册成功!", detail); //return new { code = 0, message = "注册成功!", sessionkey = entity.Key, username = "", userimg = m.UserImg }; } } @@ -144,42 +140,31 @@ namespace COMCMS.Web.Controllers.api /// /// [HttpGet] - public object SyncWeixinInfo(string sessionkey, string userInfo, int inviteid = 0, string random = "", string timeStamp = "", string signature = "") + public ReJson SyncWeixinInfo(string sessionkey, string userInfo, int inviteid = 0, string random = "", string timeStamp = "", string signature = "") { - if (!AutoCheckQueryStringSignature()) - { - return reJson; - } if (string.IsNullOrEmpty(sessionkey)) { - reJson.code = 5003; - reJson.message = "登录状态失败"; - return reJson; + return new ReJson(5003,"登录状态失败"); } WXAppSession entity = WXAppSession.Find(WXAppSession._.Key == sessionkey); if (entity == null) { - reJson.message = "未找到登录状态!"; - return reJson; + return new ReJson("未找到登录状态!"); } if (string.IsNullOrEmpty(userInfo)) { - reJson.message = "用户信息错误!"; - return reJson; + return new ReJson("用户信息错误!"); } WXAppUserInfo info = JsonConvert.DeserializeObject(userInfo); if (string.IsNullOrEmpty(info.avatarUrl)) { - reJson.message = "微信用户信息错误!"; - return reJson; + return new ReJson("微信用户信息错误!"); } //获取用户 Member my = Member.FindById(entity.UId); if (my == null) { - reJson.code = 40000; - reJson.message = "系统找不到本用户!"; - return reJson; + return new ReJson(40000, "系统找不到本用户!"); } //同步用户信息 my.Country = info.country; @@ -200,22 +185,20 @@ namespace COMCMS.Web.Controllers.api } my.Update(); - reJson.code = 0; - reJson.message = "同步信息成功!"; - reJson.detail = new { sessionkey = entity.Key, username = info.nickName, userimg = info.avatarUrl }; - return reJson; + var detail = new { sessionkey = entity.Key, username = info.nickName, userimg = info.avatarUrl }; + return new ReJson(0, "同步信息成功!", detail); } #endregion - #region 测试 - [HttpGet] - public object Test() - { + //#region 测试 + //[HttpGet] + //public object Test() + //{ - reJson.code = 0; - reJson.message = "测试信息,成功!"; - return reJson; - } - #endregion + // reJson.code = 0; + // reJson.message = "测试信息,成功!"; + // return reJson; + //} + //#endregion } } \ No newline at end of file diff --git a/COMCMS.Web/ExceptionHandler/ResultExceptionHandler.cs b/COMCMS.Web/ExceptionHandler/ResultExceptionHandler.cs new file mode 100644 index 0000000..b7d13ed --- /dev/null +++ b/COMCMS.Web/ExceptionHandler/ResultExceptionHandler.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using COMCMS.Web.Common; +using COMCMS.Web.Controllers.api; +using Lib.Core.MiddlewareExtension; +using Microsoft.AspNetCore.Http; + +namespace COMCMS.Web.ExceptionHandler +{ + public class ResultExceptionHandler : IExceptionHandler + { + public async Task ExceptionHandle(HttpContext context, Exception exception) + { + string message = exception.Message; + + ReJSON error = new ReJSON(message); + + await context.Response.WriteAsync(error.ToJson()); + } + } +} diff --git a/COMCMS.Web/Filter/CheckFilter.cs b/COMCMS.Web/Filter/CheckFilter.cs new file mode 100644 index 0000000..9691e60 --- /dev/null +++ b/COMCMS.Web/Filter/CheckFilter.cs @@ -0,0 +1,94 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using COMCMS.Common; +using COMCMS.Web.Common; +using COMCMS.Web.Controllers.api; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc.Filters; + +namespace COMCMS.Web.Filter +{ + public class CheckFilterAttribute : ActionFilterAttribute + { + public override async void OnActionExecuting(ActionExecutingContext context) + { + if (!context.ModelState.IsValid) + { + var error = string.Empty; + + foreach (var key in context.ModelState.Keys) + { + var state = context.ModelState[key]; + if (state.Errors.Any()) + { + error = string.Join("\r\n", state.Errors.ToList().ConvertAll(item => item.ErrorMessage)); + if (error.Equals(string.Empty)) + error = string.Join("\r\n", state.Errors.ToList().ConvertAll(item => item.Exception.Message)); + break; + } + } + + throw new Exception(error); + } + + var notVali = ValiSignature(context.HttpContext); + + if (notVali == null) + { + await context.HttpContext.Response.WriteAsync(notVali.ToJson()); + } + } + + private ReJSON ValiSignature(HttpContext context) + { + var Request = context.Request; + + var queryStrings = Request.Query; + List keys = new List(); + //string[] keys = HttpContext.Current.Request.QueryString.AllKeys; + if (queryStrings == null) + { + throw new Exception("queryStrings Is Null"); + } + foreach (var item in queryStrings.Keys) + { + keys.Add(item); + } + SortedDictionary pars = new SortedDictionary(); + string signature = ""; + foreach (var k in keys) + { + if (k != "signature") + { + string v = Request.Query[k]; + pars.Add(k, v); + } + else + { + signature = Request.Query[k]; + } + } + //没有签名返回错误 + if (string.IsNullOrEmpty(signature)) + throw new Exception("signature Is Null"); + + if (!MySign.CheckSign(pars, signature)) + { + + return new ReJSON(40004, "signature 错误!"); + } + //判断是否超时 + string timeStamp = pars["timeStamp"]; + //判断时间有效性 + DateTime postTime = Utils.StampToDateTime(timeStamp); + if (postTime < DateTime.Now.AddSeconds(-120))//30秒有效期 + { + return new ReJSON(40004, "signature 错误!", 1); + } + + return null; + } + } +} diff --git a/COMCMS.Web/Startup.cs b/COMCMS.Web/Startup.cs index e4ef5f9..2c675e4 100644 --- a/COMCMS.Web/Startup.cs +++ b/COMCMS.Web/Startup.cs @@ -15,6 +15,8 @@ using Microsoft.AspNetCore.Mvc; using COMCMS.Common; using COMCMS.Web.Models; using COMCMS.Web.Common; +using COMCMS.Web.ExceptionHandler; +using Lib.Core.MiddlewareExtension.Extension; namespace COMCMS.Web { @@ -118,6 +120,8 @@ namespace COMCMS.Web ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); + app.UseMiddlewareExtension(new ResultExceptionHandler()); + //加入HttpContext //MyHttpContext.ServiceProvider = svp; } diff --git a/Lib.Core/Lib.Core.csproj b/Lib.Core/Lib.Core.csproj new file mode 100644 index 0000000..574c0e6 --- /dev/null +++ b/Lib.Core/Lib.Core.csproj @@ -0,0 +1,11 @@ + + + + netstandard2.0 + + + + + + + diff --git a/Lib.Core/MiddlewareExtension/ExceptionHandlingMiddleware.cs b/Lib.Core/MiddlewareExtension/ExceptionHandlingMiddleware.cs new file mode 100644 index 0000000..f3d5920 --- /dev/null +++ b/Lib.Core/MiddlewareExtension/ExceptionHandlingMiddleware.cs @@ -0,0 +1,33 @@ +using System; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; + +namespace Lib.Core.MiddlewareExtension +{ + public class ExceptionHandlingMiddleware + { + private readonly RequestDelegate _next; + private readonly IExceptionHandler _exceptionHandler; + + public ExceptionHandlingMiddleware(RequestDelegate next, IExceptionHandler exceptionHandler) + { + _next = next; + _exceptionHandler = exceptionHandler; + } + + public async Task Invoke(HttpContext context, ILogger logger) + { + try + { + await _next(context); + } + catch (Exception ex) + { + logger.LogDebug(ex, "ExceptionHandlingMiddleware"); + + await _exceptionHandler.ExceptionHandle(context, ex); + } + } + } +} diff --git a/Lib.Core/MiddlewareExtension/Extension/MiddlewareExtension.cs b/Lib.Core/MiddlewareExtension/Extension/MiddlewareExtension.cs new file mode 100644 index 0000000..c8f30ee --- /dev/null +++ b/Lib.Core/MiddlewareExtension/Extension/MiddlewareExtension.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Microsoft.AspNetCore.Builder; + +namespace Lib.Core.MiddlewareExtension.Extension +{ + public static class MiddlewareExtension + { + public static IApplicationBuilder UseMiddlewareExtension(this IApplicationBuilder app, IExceptionHandler exceptionHandler) + { + app.UseMiddleware(exceptionHandler); + + return app; + } + } +} diff --git a/Lib.Core/MiddlewareExtension/IExceptionHandler.cs b/Lib.Core/MiddlewareExtension/IExceptionHandler.cs new file mode 100644 index 0000000..8a95e9a --- /dev/null +++ b/Lib.Core/MiddlewareExtension/IExceptionHandler.cs @@ -0,0 +1,11 @@ +using System; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; + +namespace Lib.Core.MiddlewareExtension +{ + public interface IExceptionHandler + { + Task ExceptionHandle(HttpContext context, Exception exception); + } +} \ No newline at end of file