asp.net core 2.0使用JWT认证园子里已经有挺多帖子了,但开发中发现认证未授权情况下返回的401状态码是没有任何信息的,业务中可能有需要返回一串错误的Json信息。在这里我分享一个自定义错误页面内容信息的方法,使用该扩展方法还可以捕获异常,将异常信息也转为json。
1.新建一个Api接口统一返回类ApiResult.cs(可替换成自己的)。
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.cs
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.UseErrorHandling();
完整的Configure方法
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格式。
postman中请求返回