fix vali middleware

This commit is contained in:
HTR
2018-07-02 18:15:35 +08:00
parent 2e19235619
commit 1b5155aeaa
14 changed files with 358 additions and 226 deletions
+16
View File
@@ -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<TEntity>(this TEntity entity) where TEntity : class
{
return JsonConvert.SerializeObject(entity);
}
}
}
@@ -16,9 +16,7 @@ namespace COMCMS.Web.Common
{ {
context.HttpContext.Request.ContentType = "application/json"; context.HttpContext.Request.ContentType = "application/json";
context.HttpContext.Request.Headers["Accept"] = "application/json"; context.HttpContext.Request.Headers["Accept"] = "application/json";
ReJSON model = new ReJSON(); ReJSON model = new ReJSON(5001, "执行错误:" + context.Exception.Message);
model.code = 5001;
model.message = "执行错误:"+ context.Exception.Message;
context.Result = new JsonResult(model); context.Result = new JsonResult(model);
base.OnException(context); base.OnException(context);
} }
@@ -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<string, string> 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 的签名
/// <summary>
/// 自动验证QueryString 的签名
/// </summary>
/// <returns></returns>
public bool AutoCheckQueryStringSignature()
{
var queryStrings = Request.Query;
List<string> keys = new List<string>();
//string[] keys = HttpContext.Current.Request.QueryString.AllKeys;
if (queryStrings == null)
{
return false;
}
foreach (var item in queryStrings.Keys)
{
keys.Add(item);
}
SortedDictionary<string, string> pars = new SortedDictionary<string, string>();
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
{
/// <summary>
/// 返回代码 0 为正确
/// </summary>
public int code { get; set; } = 40000;
/// <summary>
/// 提示语
/// </summary>
public string message { get; set; }
/// <summary>
/// 是否重新加载
/// </summary>
public int isReload { get; set; } = 0;
/// <summary>
/// 数据详情 object
/// </summary>
public object detail { get; set; }
}
#endregion
}
+19 -27
View File
@@ -5,6 +5,7 @@ using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using COMCMS.Common; using COMCMS.Common;
using COMCMS.Core; using COMCMS.Core;
using COMCMS.Web.Filter;
using XCode; using XCode;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 // 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 namespace COMCMS.Web.Controllers.api
{ {
public class IndexController : APIBaseController public class IndexController : Controller
{ {
// GET: api/<controller> // GET: api/<controller>
[HttpGet] [HttpGet]
@@ -22,7 +23,7 @@ namespace COMCMS.Web.Controllers.api
return cfg; return cfg;
} }
#region 测试验签 //#region 测试验签
/// <summary> /// <summary>
/// 测试验签 /// 测试验签
/// </summary> /// </summary>
@@ -31,31 +32,22 @@ namespace COMCMS.Web.Controllers.api
/// <param name="timeStamp"></param> /// <param name="timeStamp"></param>
/// <param name="signature"></param> /// <param name="signature"></param>
/// <returns></returns> /// <returns></returns>
[HttpGet] //[HttpGet]
public object CheckSign(string id, string random = "", string timeStamp = "", string signature = "") //[CheckFilter]
{ //public ReJSON CheckSign(string id, string random = "", string timeStamp = "", string signature = "")
if (!AutoCheckQueryStringSignature()) //{
{ // return new ReJSON("验签成功!");
reJson.message = "验签失败!"; //}
return reJson; //#endregion
}
else
{
reJson.code = 0;
reJson.message = "验签成功!";
return reJson;
}
}
#endregion
#region 测试出错 //#region 测试出错
[HttpGet] //[HttpGet]
public object GetTest() //public object GetTest()
{ //{
int a = 1,b=0; // int a = 1,b=0;
var c = a / b; // var c = a / b;
return reJson; // return reJson;
} //}
#endregion //#endregion
} }
} }
+33 -29
View File
@@ -5,6 +5,7 @@ using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using COMCMS.Common; using COMCMS.Common;
using COMCMS.Core; using COMCMS.Core;
using COMCMS.Web.Filter;
using XCode; using XCode;
using NewLife.Log; using NewLife.Log;
using Senparc.Weixin.MP; using Senparc.Weixin.MP;
@@ -16,45 +17,46 @@ namespace COMCMS.Web.Controllers.api
/// <summary> /// <summary>
/// 支付API /// 支付API
/// </summary> /// </summary>
public class PaymentController : APIBaseController public class PaymentController : Controller
{ {
#region 微信小程序订单支付 #region 微信小程序订单支付
[HttpGet] [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); Order entity = Order.Find(Order._.OrderNum == ordernum);
if (entity == null) if (entity == null)
{ {
reJson.code = 40000; //reJson.code = 40000;
reJson.message = "系统找不到本订单!"; //reJson.message = "系统找不到本订单!";
return reJson; //return reJson;
return new ReJson(40000, "系统找不到本订单!");
} }
//判断订单状态 //判断订单状态
if (entity.OrderStatus == Utils.OrdersState[3]) if (entity.OrderStatus == Utils.OrdersState[3])
{ {
reJson.code = 40000; //reJson.code = 40000;
reJson.message = "已完成订单不允许支付!"; //reJson.message = "已完成订单不允许支付!";
return reJson; //return reJson;
return new ReJson(40000, "已完成订单不允许支付!");
} }
if (entity.PaymentStatus != Utils.PaymentState[0]) if (entity.PaymentStatus != Utils.PaymentState[0])
{ {
reJson.code = 40000; //reJson.code = 40000;
reJson.message = "当前订单支付状态不允许支付!"; //reJson.message = "当前订单支付状态不允许支付!";
return reJson; //return reJson;
return new ReJson(40000, "当前订单支付状态不允许支付!");
} }
//获取用户并判断是否是已经注册用户 //获取用户并判断是否是已经注册用户
Member my = Member.FindById(entity.UId); Member my = Member.FindById(entity.UId);
if (my == null || string.IsNullOrEmpty(my.WeixinAppOpenId)) if (my == null || string.IsNullOrEmpty(my.WeixinAppOpenId))
{ {
reJson.code = 40000; //reJson.code = 40000;
reJson.message = "用户状态错误,无法使用本功能!"; //reJson.message = "用户状态错误,无法使用本功能!";
return reJson; //return reJson;
return new ReJson(40000, "用户状态错误,无法使用本功能!");
} }
//开始生成支付订单 //开始生成支付订单
OnlinePayOrder model = new OnlinePayOrder(); OnlinePayOrder model = new OnlinePayOrder();
@@ -112,9 +114,10 @@ namespace COMCMS.Web.Controllers.api
if (result.return_code == "FAIL") if (result.return_code == "FAIL")
{ {
reJson.code = 40005; //reJson.code = 40005;
reJson.message = result.return_msg; //reJson.message = result.return_msg;
return reJson; //return reJson;
return new ReJson(40005, result.return_msg);
} }
string nativeReqSign = res.CreateMd5Sign("key", TenPayV3Info.Key); string nativeReqSign = res.CreateMd5Sign("key", TenPayV3Info.Key);
//https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=3 //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 }; dynamic detail = new { timeStamp = rtimeStamp, nonceStr = nonceStr, package = package, signType = "MD5", paySign = paySign };
reJson.code = 0; //reJson.code = 0;
reJson.message = "下单成功!"; //reJson.message = "下单成功!";
reJson.detail = detail; //reJson.detail = detail;
return reJson; //return reJson;
return new ReJson(40000, "下单成功!", detail);
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -136,9 +140,9 @@ namespace COMCMS.Web.Controllers.api
res.SetParameter("return_msg", "统一下单失败"); res.SetParameter("return_msg", "统一下单失败");
XTrace.WriteLine($"统一下单失败:{ex.Message}"); XTrace.WriteLine($"统一下单失败:{ex.Message}");
reJson.code = 40005; //reJson.code = 40005;
reJson.message = "统一下单失败,请联系管理员!"; //reJson.message = "统一下单失败,请联系管理员!";
return reJson; return new ReJson(40005, "统一下单失败,请联系管理员!");
} }
} }
#endregion #endregion
+62
View File
@@ -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;
}
/// <summary>
/// 返回代码 0 为正确
/// </summary>
public int code { get; set; } = 40000;
/// <summary>
/// 提示语
/// </summary>
public string message { get; set; }
/// <summary>
/// 是否重新加载
/// </summary>
public int isReload { get; set; } = 0;
/// <summary>
/// 数据详情 object
/// </summary>
public object detail { get; set; }
}
#endregion
}
+34 -51
View File
@@ -9,6 +9,7 @@ using COMCMS.Core;
using COMCMS.Core.Models; using COMCMS.Core.Models;
using XCode; using XCode;
using System.Web; using System.Web;
using COMCMS.Web.Filter;
using NewLife.Log; using NewLife.Log;
using static COMCMS.Web.Models.APIModels; using static COMCMS.Web.Models.APIModels;
using Newtonsoft.Json; using Newtonsoft.Json;
@@ -16,7 +17,7 @@ using Newtonsoft.Json.Linq;
namespace COMCMS.Web.Controllers.api namespace COMCMS.Web.Controllers.api
{ {
public class UserController : APIBaseController public class UserController : Controller
{ {
#region 用户登录 #region 用户登录
/// <summary> /// <summary>
@@ -28,16 +29,12 @@ namespace COMCMS.Web.Controllers.api
/// <param name="signature"></param> /// <param name="signature"></param>
/// <returns></returns> /// <returns></returns>
[HttpGet] [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)) if (string.IsNullOrEmpty(code))
{ {
reJson.message = "请允许用户授权信息!"; return new ReJson("请允许用户授权信息!");
return reJson;
} }
Config cfg = Config.GetSystemConfig(); Config cfg = Config.GetSystemConfig();
string appid = cfg.WXAppId;// ConfigurationManager.AppSettings["wxappAppId"]; string appid = cfg.WXAppId;// ConfigurationManager.AppSettings["wxappAppId"];
@@ -51,8 +48,7 @@ namespace COMCMS.Web.Controllers.api
if (!string.IsNullOrEmpty(json.errcode)) if (!string.IsNullOrEmpty(json.errcode))
{ {
XTrace.WriteLine("微信服务器回调失败:" + json.errcode); XTrace.WriteLine("微信服务器回调失败:" + json.errcode);
reJson.message = "注册失败,请联系管理员。" + json.errcode; return new ReJson("注册失败,请联系管理员。" + json.errcode);
return reJson;
} }
if (Member.FindCount(Member._.WeixinAppOpenId == json.openid, null, null, 0, 0) > 0) if (Member.FindCount(Member._.WeixinAppOpenId == json.openid, null, null, 0, 0) > 0)
{ {
@@ -60,9 +56,9 @@ namespace COMCMS.Web.Controllers.api
if (my == null) if (my == null)
{ {
XTrace.WriteLine("登录成功,但是系统找不到用户:"); XTrace.WriteLine("登录成功,但是系统找不到用户:");
reJson.code = 5003; //reJson.code = 5003;
reJson.message = "系统找不到本用户!"; //reJson.message = "系统找不到本用户!";
return reJson; return new ReJson(5003, "系统找不到本用户!");
} }
//如果存在,则返回个人信息 //如果存在,则返回个人信息
@@ -90,10 +86,10 @@ namespace COMCMS.Web.Controllers.api
} }
string nickName = my.Nickname; string nickName = my.Nickname;
if (!string.IsNullOrEmpty(nickName)) nickName = HttpUtility.UrlDecode(nickName); if (!string.IsNullOrEmpty(nickName)) nickName = HttpUtility.UrlDecode(nickName);
reJson.code = 0; //reJson.code = 0;
reJson.message = "登录成功!"; //reJson.message = "登录成功!";
reJson.detail = new { sessionkey = mysessionkey, username = nickName, userimg = my.UserImg }; var detail = new { sessionkey = mysessionkey, username = nickName, userimg = my.UserImg };
return reJson; return new ReJson(0, "登录成功!", detail);
//return new { code = 0, message = "登录成功", sessionkey = mysessionkey, username = nickName, userimg = my.UserImg }; //return new { code = 0, message = "登录成功", sessionkey = mysessionkey, username = nickName, userimg = my.UserImg };
} }
else else
@@ -129,10 +125,10 @@ namespace COMCMS.Web.Controllers.api
entity.AddTime = DateTime.Now; entity.AddTime = DateTime.Now;
entity.UId = m.Id; entity.UId = m.Id;
entity.Insert(); entity.Insert();
reJson.code = 0; //reJson.code = 0;
reJson.message = "注册成功!"; //reJson.message = "注册成功!";
reJson.detail = new { sessionkey = entity.Key, username = "", userimg = m.UserImg }; var detail = new { sessionkey = entity.Key, username = "", userimg = m.UserImg };
return reJson; return new ReJson(0, "注册成功!", detail);
//return new { code = 0, message = "注册成功!", sessionkey = entity.Key, username = "", userimg = m.UserImg }; //return new { code = 0, message = "注册成功!", sessionkey = entity.Key, username = "", userimg = m.UserImg };
} }
} }
@@ -144,42 +140,31 @@ namespace COMCMS.Web.Controllers.api
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[HttpGet] [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)) if (string.IsNullOrEmpty(sessionkey))
{ {
reJson.code = 5003; return new ReJson(5003,"登录状态失败");
reJson.message = "登录状态失败";
return reJson;
} }
WXAppSession entity = WXAppSession.Find(WXAppSession._.Key == sessionkey); WXAppSession entity = WXAppSession.Find(WXAppSession._.Key == sessionkey);
if (entity == null) if (entity == null)
{ {
reJson.message = "未找到登录状态!"; return new ReJson("未找到登录状态!");
return reJson;
} }
if (string.IsNullOrEmpty(userInfo)) if (string.IsNullOrEmpty(userInfo))
{ {
reJson.message = "用户信息错误!"; return new ReJson("用户信息错误!");
return reJson;
} }
WXAppUserInfo info = JsonConvert.DeserializeObject<WXAppUserInfo>(userInfo); WXAppUserInfo info = JsonConvert.DeserializeObject<WXAppUserInfo>(userInfo);
if (string.IsNullOrEmpty(info.avatarUrl)) if (string.IsNullOrEmpty(info.avatarUrl))
{ {
reJson.message = "微信用户信息错误!"; return new ReJson("微信用户信息错误!");
return reJson;
} }
//获取用户 //获取用户
Member my = Member.FindById(entity.UId); Member my = Member.FindById(entity.UId);
if (my == null) if (my == null)
{ {
reJson.code = 40000; return new ReJson(40000, "系统找不到本用户!");
reJson.message = "系统找不到本用户!";
return reJson;
} }
//同步用户信息 //同步用户信息
my.Country = info.country; my.Country = info.country;
@@ -200,22 +185,20 @@ namespace COMCMS.Web.Controllers.api
} }
my.Update(); my.Update();
reJson.code = 0; var detail = new { sessionkey = entity.Key, username = info.nickName, userimg = info.avatarUrl };
reJson.message = "同步信息成功!"; return new ReJson(0, "同步信息成功!", detail);
reJson.detail = new { sessionkey = entity.Key, username = info.nickName, userimg = info.avatarUrl };
return reJson;
} }
#endregion #endregion
#region 测试 //#region 测试
[HttpGet] //[HttpGet]
public object Test() //public object Test()
{ //{
reJson.code = 0; // reJson.code = 0;
reJson.message = "测试信息,成功!"; // reJson.message = "测试信息,成功!";
return reJson; // return reJson;
} //}
#endregion //#endregion
} }
} }
@@ -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());
}
}
}
+94
View File
@@ -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<string> keys = new List<string>();
//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<string, string> pars = new SortedDictionary<string, string>();
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;
}
}
}
+4
View File
@@ -15,6 +15,8 @@ using Microsoft.AspNetCore.Mvc;
using COMCMS.Common; using COMCMS.Common;
using COMCMS.Web.Models; using COMCMS.Web.Models;
using COMCMS.Web.Common; using COMCMS.Web.Common;
using COMCMS.Web.ExceptionHandler;
using Lib.Core.MiddlewareExtension.Extension;
namespace COMCMS.Web namespace COMCMS.Web
{ {
@@ -118,6 +120,8 @@ namespace COMCMS.Web
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
}); });
app.UseMiddlewareExtension(new ResultExceptionHandler());
//加入HttpContext //加入HttpContext
//MyHttpContext.ServiceProvider = svp; //MyHttpContext.ServiceProvider = svp;
} }
+11
View File
@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore" Version="2.1.0" />
</ItemGroup>
</Project>
@@ -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<ExceptionHandlingMiddleware> logger)
{
try
{
await _next(context);
}
catch (Exception ex)
{
logger.LogDebug(ex, "ExceptionHandlingMiddleware");
await _exceptionHandler.ExceptionHandle(context, ex);
}
}
}
}
@@ -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<ExceptionHandlingMiddleware>(exceptionHandler);
return app;
}
}
}
@@ -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);
}
}