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. 前台页面id为空--驼峰命名映射

    错误: 前台页面id为空,或其他数据映射问题(方案2) 原因: java的bean类属性和数据库字段命名不一致,查询的时候就不能把数据封装进bean类里,  在数据库字段命名规范中,通常使用下划线“_ ...

  2. 解决Mac中anaconda作图中文异常显示的问题

    说明 本篇主要针对在MAC系统中Anaconda环境下,matplotlib显示不了中文的问题,提出解决Python绘图时中文显示的方法. 运行环境 macOS Mojave 10.14.6 Pyth ...

  3. Nginx负载均衡的详细配置 + Keepalived使用

    1,话不多说, 这里我们来说下很重要的负载均衡, 那么什么是负载均衡呢? 由于目前现有网络的各个核心部分随着业务量的提高,访问量和数据流量的快速增长,其处理能力和计算强度也相应地增大,使得单一的服务器 ...

  4. 尚学堂 217 java中的字节码操作2

    package com.bjsxt.test; @Author(name="gaoqi", year=2014) public class Emp { private int em ...

  5. 搜索引擎-SHODAN

    shodan这个搜索引擎不会爬取网页内容,而是爬取所有的联网设备. 这个搜索引擎还是很强大的,下图就是我用shodan查自己的案例服务器的结果: 如图,可以查到这台服务器安装了wdcp管理面板,黑客完 ...

  6. kubernetes资源均衡器Descheduler

    背景 Kubernetes中的调度是将待处理的pod绑定到节点的过程,由Kubernetes的一个名为kube-scheduler的组件执行.调度程序的决定,无论是否可以或不能调度容器,都由其可配置策 ...

  7. 一条SQL删除重复记录,重复的只保留一条

    情景: 我们的数据库中可能会存在很多因各种原因而重复的记录,我们需要对这些重复的记录进行删除,每组组重复的记录只保留一条就行 例如我们有这么个表:两个框框都是有重复记录的,红框和绿框都只需要留下一条, ...

  8. openstack Rocky 社区版部署1.2 安装ntp service

    一.controller节点安装ntp 1 安装ntp服务 yum install chrony 2 Edit the chrony.conf file and add, change, or rem ...

  9. 扫描U盘

    编辑器加载中...int CSendUDiskDlg::SearchUDisk(void) { int nCount, i; char szDriver[3]; nCount = 0; szDrive ...

  10. File and Code Templates IN IDEA

    File and Code Templates (文件代码模板) 如何自定义设置头文件的注释,其中包括一些作者和文件创建时间和版本的设置 先打开File->Settings(或Alt+Ctrl+ ...