asp.net core 2.0使用JWT認證園子裏已經有挺多帖子了,但開發中發現認證未受權狀況下返回的401狀態碼是沒有任何信息的,業務中可能有須要返回一串錯誤的Json信息。在這裏我分享一個自定義錯誤頁面內容信息的方法,使用該擴展方法還能夠捕獲異常,將異常信息也轉爲json。json
1.新建一個Api接口統一返回類ApiResult.cs(可替換成本身的)。api
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Jom.WebApi.Config { public class ApiResult { public bool Success { get; set; } = true; public string Msg { get; set; } = ""; public string Type { get; set; } = ""; public object Data { get; set; } = ""; public object DataExt { get; set; } = ""; } }
2.創建中間件ErrorHandlingMiddleware.csmvc
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Jom.WebApi.Config { public class ErrorHandlingMiddleware { private readonly RequestDelegate next; public ErrorHandlingMiddleware(RequestDelegate next) { this.next = next; } public async Task Invoke(HttpContext context) { try { await next(context); } catch (Exception ex) { var statusCode = context.Response.StatusCode; if (ex is ArgumentException) { statusCode = 200; } await HandleExceptionAsync(context, statusCode, ex.Message); } finally { var statusCode = context.Response.StatusCode; var msg = ""; if (statusCode == 401) { msg = "未受權"; } else if (statusCode == 404) { msg = "未找到服務"; } else if (statusCode == 502) { msg = "請求錯誤"; } else if (statusCode != 200) { msg = "未知錯誤"; } if (!string.IsNullOrWhiteSpace(msg)) { await HandleExceptionAsync(context, statusCode, msg); } } } //異常錯誤信息捕獲,將錯誤信息用Json方式返回 private static Task HandleExceptionAsync(HttpContext context, int statusCode, string msg) { var result = JsonConvert.SerializeObject(new ApiResult() { Success=false,Msg=msg,Type= statusCode.ToString() }); context.Response.ContentType = "application/json;charset=utf-8"; return context.Response.WriteAsync(result); } } //擴展方法 public static class ErrorHandlingExtensions { public static IApplicationBuilder UseErrorHandling(this IApplicationBuilder builder) { return builder.UseMiddleware<ErrorHandlingMiddleware>(); } } }
3.最後只要在Startup.cs中的Configure方法中加上一句,在Startup.cs中添加引用using Jom.WebApi.Config;使用擴展方法ErrorHandlingExtensions()使用錯誤碼處理中間件。app
//請求錯誤提示配置 app.UseErrorHandling();
完整的Configure方法asp.net
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } //請求錯誤提示配置 app.UseErrorHandling(); //使用認證受權 app.UseAuthentication(); //使用mvc app.UseMvc(routes => { routes.MapRoute( name: "default", template: "api/{controller}/{action}/{id?}", defaults: new { controller = "Values", action = "Get" }); }); }
最後就完成了自定義401頁面內容,同時還能夠定義其餘狀態碼如403,404,502,503等等,同時api接口報異常也將轉化爲特定的JSON格式。async
postman中請求返回post