應用場景
有的時候,接口請求會返回一些系統的狀態碼,如404,401,403等,我們會希望自定義這些返回消息,這個時候我們可以自定義一個中間件來在消息返回之前處理消息。
定義中間件
Model項目新建ErrorModel,定義錯誤消息返回格式。
public class ErrorModel { /// <summary> /// 狀態碼 /// </summary> public int code { get; set; } = 500; /// <summary> /// 錯誤信息 /// </summary> public string msg { get; set; } /// <summary> /// 錯誤詳情 /// </summary> public string detail { get; set; } /// <summary> /// 時間戳 /// </summary> public string timestamp { get; set; } = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); }
Common的JsonHelper類里面新加一個方法
/// <summary> /// 轉Json回HttpResponseMessage /// </summary> /// <param name="code"></param> /// <param name="result"></param> /// <returns></returns> public static string toJson(object result) { return Newtonsoft.Json.JsonConvert.SerializeObject(result); }
項目新建Middleware文件夾,新建CustomExceptionMiddleware.cs
public class CustomExceptionMiddleware { private readonly RequestDelegate _next; private readonly ILoggerHelper _logger; public CustomExceptionMiddleware(RequestDelegate next, ILoggerHelper logger) { _next = next; _logger = logger; } public async Task Invoke(HttpContext httpContext) { try { await _next(httpContext); } catch (Exception ex) { _logger.Error(ex.Message, ex); // 日志記錄 await HandleExceptionAsync(httpContext, ex.Message); } finally { var statusCode = httpContext.Response.StatusCode; var msg = ""; switch (statusCode) { case 401: msg = "未授權"; break; case 403: msg = "拒絕訪問"; break; case 404: msg = "未找到服務"; break; case 405: msg = "405 Method Not Allowed"; break; case 502: msg = "請求錯誤"; break; } if (!string.IsNullOrWhiteSpace(msg)) { await HandleExceptionAsync(httpContext, msg); } } } /// private async Task HandleExceptionAsync(HttpContext httpContext, string msg) { ErrorModel error = new ErrorModel { code = httpContext.Response.StatusCode, msg = msg }; var result = JsonHelper.toJson(error); httpContext.Response.ContentType = "application/json;charset=utf-8"; await httpContext.Response.WriteAsync(result).ConfigureAwait(false); } } // Extension method used to add the middleware to the HTTP request pipeline. public static class CustomExceptionMiddlewareExtensions { public static IApplicationBuilder UseCustomExceptionMiddleware(this IApplicationBuilder builder) { return builder.UseMiddleware<CustomExceptionMiddleware>(); } }
使用中間件
startup.cs的Configure方法注冊中間件
app.UseCustomExceptionMiddleware();
運行項目,訪問一個需要認證的接口,可以看到消息已經是我們自定義的格式了。