.Net Core3.0 WebApi 项目框架搭建 十三:自定义全局消息返回过滤中间件
2020-12-29 12:29
标签:build info false conf date tom 日志 项目 style 有的时候,接口请求会返回一些系统的状态码,如404,401,403等,我们会希望自定义这些返回消息,这个时候我们可以自定义一个中间件来在消息返回之前处理消息。 Model项目新建ErrorModel,定义错误消息返回格式。 Common的JsonHelper类里面新加一个方法 项目新建Middleware文件夹,新建CustomExceptionMiddleware.cs startup.cs的Configure方法注册中间件 运行项目,访问一个需要认证的接口,可以看到消息已经是我们自定义的格式了。 .Net Core3.0 WebApi 项目框架搭建 十三:自定义全局消息返回过滤中间件 标签:build info false conf date tom 日志 项目 style 原文地址:https://www.cnblogs.com/huguodong/p/13287648.html应用场景
定义中间件
public class ErrorModel
{
///
///
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
使用中间件
app.UseCustomExceptionMiddleware();
上一篇:win10如何设置锁屏后不熄屏
文章标题:.Net Core3.0 WebApi 项目框架搭建 十三:自定义全局消息返回过滤中间件
文章链接:http://soscw.com/index.php/essay/39059.html