参考资料: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
return app;
}
}
Middleware
public class ExceptionHandleMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
public ExceptionHandleMiddleware( RequestDelegate next, ILogger
{
_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
{
///
T Data { get; }
}
Result
///
public class ResultModel
{
///
[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
{
Successful = true;
Data = data;
Msg = msg;
return this;
}
///
/// 说明
public ResultModel
{
Successful = false;
Msg = msg;
return this;
}
}
///
public static class ResultModel
{
///
/// 返回数据
///
public static IResultModel Success
{
return new ResultModel
}
///
///
public static IResultModel Success()
{
return Success
}
///
/// 错误信息
///
public static IResultModel Failed
{
return new ResultModel
}
///
///
public static IResultModel Failed(string error = null)
{
return Failed
}
///
///
///
public static IResultModel Result
{
return success ? Success
}
///
///
///
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
手机扫一扫
移动阅读更方便
你可能感兴趣的文章