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<ExceptionHandleMiddleware>();//UseMiddleware添加中间件
return app;
}
}
 
 Middleware
public  class ExceptionHandleMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
public ExceptionHandleMiddleware( RequestDelegate next, ILogger<ExceptionHandleMiddleware> 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
/// <summary>
/// 返回结果模型接口
/// </summary>
public interface IResultModel
{
/// <summary>
/// 是否成功
/// </summary>
[JsonIgnore]
bool Successful { get; }
/// <summary>
/// 错误
/// </summary>
string Msg { get; }
}
/// <summary>
/// 返回结果模型泛型接口
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IResultModel<T> : IResultModel
{
/// <summary>
/// 返回数据
/// </summary>
T Data { get; }
}
Result
/// <summary>
/// 返回结果
/// </summary>
public class ResultModel<T> : IResultModel<T>
{
/// <summary>
/// 处理是否成功
/// </summary>
[JsonIgnore]
public bool Successful { get; private set; }
/// <summary>
/// 错误信息
/// </summary>
public string Msg { get; private set; }
/// <summary>
/// 状态码
/// </summary>
public int Code => Successful ? : ;
/// <summary>
/// 返回数据
/// </summary>
public T Data { get; private set; }
/// <summary>
/// 成功
/// </summary>
/// <param name="data">数据</param>
/// <param name="msg">说明</param>
public ResultModel<T> Success(T data = default, string msg = "success")
{
Successful = true;
Data = data;
Msg = msg;
return this;
}
/// <summary>
/// 失败
/// </summary>
/// <param name="msg">说明</param>
public ResultModel<T> Failed(string msg = "failed")
{
Successful = false;
Msg = msg;
return this;
}
}
/// <summary>
/// 返回结果
/// </summary>
public static class ResultModel
{
/// <summary>
/// 成功
/// </summary>
/// <param name="data">返回数据</param>
/// <returns></returns>
public static IResultModel Success<T>(T data = default(T))
{
return new ResultModel<T>().Success(data);
}
/// <summary>
/// 成功
/// </summary>
/// <returns></returns>
public static IResultModel Success()
{
return Success<string>();
}
/// <summary>
/// 失败
/// </summary>
/// <param name="error">错误信息</param>
/// <returns></returns>
public static IResultModel Failed<T>(string error = null)
{
return new ResultModel<T>().Failed(error ?? "failed");
}
/// <summary>
/// 失败
/// </summary>
/// <returns></returns>
public static IResultModel Failed(string error = null)
{
return Failed<string>(error);
}
/// <summary>
/// 根据布尔值返回结果
/// </summary>
/// <param name="success"></param>
/// <returns></returns>
public static IResultModel Result<T>(bool success)
{
return success ? Success<T>() : Failed<T>();
}
/// <summary>
///
/// </summary>
/// <param name="success"></param>
/// <returns></returns>
public static IResultModel Result(bool success)
{
return success ? Success() : Failed();
}
/// <summary>
/// 数据已存在
/// </summary>
/// <returns></returns>
public static IResultModel HasExists => Failed("数据已存在");
/// <summary>
/// 数据不存在
/// </summary>
public static IResultModel NotExists => Failed("数据不存在");
}
 
到此中间件已经添加完成

ASP.NET CORE之中间件-自定义异常中间件的更多相关文章

  1. 在ASP.NET Core 中使用Cookie中间件

    在ASP.NET Core 中使用Cookie中间件 ASP.NET Core 提供了Cookie中间件来序列化用户主题到一个加密的Cookie中并且在后来的请求中校验这个Cookie,再现用户并且分 ...

  2. asp.net core mvc 管道之中间件

    asp.net core mvc 管道之中间件 http请求处理管道通过注册中间件来实现各种功能,松耦合并且很灵活 此文简单介绍asp.net core mvc中间件的注册以及运行过程 通过理解中间件 ...

  3. 在ASP.NET Core 中使用Cookie中间件 (.net core 1.x适用)

    在ASP.NET Core 中使用Cookie中间件 ASP.NET Core 提供了Cookie中间件来序列化用户主题到一个加密的Cookie中并且在后来的请求中校验这个Cookie,再现用户并且分 ...

  4. Asp.Net Core入门之自定义中间件

    什么是中间件? 这里引用官方解释: 中间件是用于组成应用程序管道来处理请求和响应的组件.管道内的每一个组件都可以选择是否将请求交给下一个组件.并在管道中调用下一个组件之前和之后执行某些操作.请求委托被 ...

  5. asp.net core 3.1 自定义中间件实现jwt token认证

    asp.net core 3.1 自定义中间件实现jwt token认证 话不多讲,也不知道咋讲!直接上代码 认证信息承载对象[user] /// <summary> /// 认证用户信息 ...

  6. ASP.NET Core 使用 URL Rewrite 中间件实现 HTTP 重定向到 HTTPS

    在传统 ASP.NET 程序中,我们可以通过配置 IIS 的“URL 重写”功能实现将 HTTP 请求重定向为 HTTPS .但是该方法在 ASP.NET Core 应用中不再工作.在 ASP.NET ...

  7. asp.net core中写入自定义中间件

    首先要明确什么是中间件?微软官方解释:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/?tabs=aspnet ...

  8. ASP.NET Core 2.2在中间件内使用有作用域的服务

    服务生存期 为每个注册的服务选择适当的生存期.可以使用以下生存期配置ASP.NET Core服务: 暂时 暂时生存期服务 (AddTransient) 是每次从服务容器进行请求时创建的. 这种生存期适 ...

  9. ASP.NET CORE 管道模型及中间件使用解读

    说到ASP.NET CORE 管道模型不得不先来看看之前的ASP.NET 的管道模型,两者差异很大,.NET CORE 3.1 后完全重新设计了框架的底层,.net core 3.1 的管道模型更加灵 ...

随机推荐

  1. 研华advantech-凌华ADLINK板卡运动控制卡

    研华advantech:6路独立D/A输出12位分辨率双缓冲D/A转换器多种电压范围:+/-10V,+/-5V,0—+5V,0—+10V和4—20mA电流环(汇)16路数字量输入及16路数字量输出 P ...

  2. Andrew Ng - 深度学习工程师 - Part 1. 神经网络和深度学习(Week 4. 深层神经网络)

     =================第2周 神经网络基础=============== ===4.1  深层神经网络=== Although for any given problem it migh ...

  3. 团队Github实践训练

    这个作业属于哪个课程 软件工程 (福州大学至诚学院 - 计算机工程系) 团队名称 WeChair 这个作业要求在哪里 团队Github实践训练 这个作业的目标 通过github实现团队协作编码 作业正 ...

  4. 再看rabbitmq的交换器和队列的关系

    最近又要用到rabbitmq,业务上要求服务器只发一次消息,需要多个客户端都去单独消费.但我们知道rabbitmq的机制里,每个队列里的消息只能消费一次,所以客户端要单独消费信息,就必须得每个客户端单 ...

  5. vue学习第二天:Vue跑马灯效果制作

    分析: 1. 给开始按钮绑定一个点击事件 2.在按钮的事件处理函数中,写相关的业务代码 3.拿到msg字符串 4.调用字符串的substring来进行字符串的截取操作 5.重新赋值利用vm实例的特性来 ...

  6. 【DMCP】2020-CVPR-DMCP Differentiable Markov Channel Pruning for Neural Networks-论文阅读

    DMCP 2020-CVPR-DMCP Differentiable Markov Channel Pruning for Neural Networks Shaopeng Guo(sensetime ...

  7. [ C++ ] 勿在浮沙筑高台 —— 拾遗

    explicit 主要用于处理一个参数的构造函数,使其不用于隐式类型转换(防止二义性) operator->() C++设计 ->可以一直保留下去 仿函数 仿函数会隐式继承他们中的一个(详 ...

  8. TestNG配合catubuter统计单元测试的代码覆盖率

    build-testNG.xml对应的ant脚本为 <?xml version="1.0" encoding="UTF-8"?> <proje ...

  9. linux网络编程-socket(36)

    进程是程序的一次动态执行的过程,进程是短暂的. 一个程序可以对应多个进程,可以打开多个记事本程序,存在多个进程. 线程是进程内部中的控制序列,一个进程至少有一个执行线路. 一个进程可以存在多个线程

  10. Codeforces Round #652 (Div. 2) 总结

    A:问正n边形的一条边和x轴平行的时候有没有一条边和y轴重合,直接判断n是否是4的倍数 #include <iostream> #include <cstdio> #inclu ...