ASP.NET CORE之中间件-自定义异常中间件
阅读原文时间:2023年07月15日阅读:1

参考资料:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/?view=aspnetcore-3.1

1、一般Asp.Net Core 创建项目后 StartUp文件中存在 StartUp、ConfigureServices 、Configure 函数或方法

2、中间件一般在Configure中配置或启用

不多说了,直接操作

一、创建项目(.NetCore 3.1)

  建议创建API项目便于后续测试验证,因为本人只是Demo创建一个空API显得更为整洁

创建完成后StartUp类

public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
});
}
}

 2、创建扩展类、中间件、结果类

    

   Extension

public static class ApplicationBuilderExtensions
{
public static IApplicationBuilder UseExceptionHandle(this IApplicationBuilder app)
{
app.UseMiddleware();//UseMiddleware添加中间件
return app;
}
}

 Middleware

public class ExceptionHandleMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
public ExceptionHandleMiddleware( RequestDelegate next, ILogger logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext httpContext)
{
try
{
await _next(httpContext);
}
catch (Exception ex)
{
await HandleExceptionAsync(httpContext, ex);
}
}
private Task HandleExceptionAsync(HttpContext context, Exception exception)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var error = exception.ToString();
_logger.LogError(error);
return context.Response.WriteAsync(JsonConvert.SerializeObject(ResultModel.Failed(error), new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
}));
}
}

IResult

///

/// 返回结果模型接口 ///
public interface IResultModel
{
/// /// 是否成功 ///
[JsonIgnore]
bool Successful { get; }
/// /// 错误 ///
string Msg { get; }
}
/// /// 返回结果模型泛型接口 ///
///
public interface IResultModel : IResultModel
{
/// /// 返回数据 ///
T Data { get; }
}

Result

///

/// 返回结果 ///
public class ResultModel : IResultModel
{
/// /// 处理是否成功 ///
[JsonIgnore]
public bool Successful { get; private set; }
/// /// 错误信息 ///
public string Msg { get; private set; }
/// /// 状态码 ///
public int Code => Successful ? : ;
/// /// 返回数据 ///
public T Data { get; private set; }
/// /// 成功 ///
/// 数据
/// 说明
public ResultModel Success(T data = default, string msg = "success")
{
Successful = true;
Data = data;
Msg = msg;
return this;
}
/// /// 失败 ///
/// 说明
public ResultModel Failed(string msg = "failed")
{
Successful = false;
Msg = msg;
return this;
}
}
/// /// 返回结果 ///
public static class ResultModel
{
/// /// 成功 ///
/// 返回数据
///
public static IResultModel Success(T data = default(T))
{
return new ResultModel().Success(data);
}
/// /// 成功 ///
///
public static IResultModel Success()
{
return Success();
}
/// /// 失败 ///
/// 错误信息
///
public static IResultModel Failed(string error = null)
{
return new ResultModel().Failed(error ?? "failed");
}
/// /// 失败 ///
///
public static IResultModel Failed(string error = null)
{
return Failed(error);
}
/// /// 根据布尔值返回结果 ///
///
///
public static IResultModel Result(bool success)
{
return success ? Success() : Failed();
}
/// /// ///
///
///
public static IResultModel Result(bool success)
{
return success ? Success() : Failed();
}
/// /// 数据已存在 ///
///
public static IResultModel HasExists => Failed("数据已存在");
/// /// 数据不存在 ///
public static IResultModel NotExists => Failed("数据不存在");
}

到此中间件已经添加完成

个人暂存:https://github.com/billowliu2/Bill.Custom.Middleware.git