ASP.NET CORE's middleware - custom exception middleware

1, there is StartUp, ConfigureServices, Configure function or method StartUp project file created after the general Asp.Net Core
2, the general configuration of the middleware or enable the Configure
Not much to say, direct operation
First, create a project (.NetCore 3.1)
  Recommends creating API project to facilitate follow-up tests to verify, because I just create an empty Demo API is much more tidy

 

 

 
When you're done StartUp category
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, to create an extension class, middleware, like result
    
   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> 
    /// Returns the model results Interface
     ///  </ Summary> 
    public  interface IResultModel 
    { 
        ///  <Summary> 
        /// success
         ///  </ Summary> 
        [JsonIgnore]
         BOOL Successful { GET ; }
         ///  <Summary> 
        /// error
         ///  </ Summary> 
        String Msg { GET ;} 
    } 
    ///  <Summary> 
    /// returns the model results generic interface
     ///  </ Summary> 
    ///  <typeparam name = "T"> </ typeparam>
    public  interface IResultModel <T> : IResultModel 
    { 
        ///  <Summary> 
        /// Returns data
         ///  </ Summary> 
        T {the Data GET ;} 
    }

 

Result
///  <Summary> 
    /// Returns result
     ///  </ Summary> 
    public  class ResultModel <T>: IResultModel <T> 
    { 
        ///  <Summary> 
        /// process succeeds
         ///  </ Summary> 
        [ JsonIgnore]
         public  BOOL Successful { GET ; Private  SET ;}
         ///  <Summary> 
        /// error
         ///  </ Summary> 
        public  String Msg { GET ; Private  SET ;}
         ///  <Summary>
        /// status code
         ///  </ Summary> 
        public  int Code => Successful? . 1 : 0 ;
         ///  <Summary> 
        /// Returns data
         ///  </ Summary> 
        public T {the Data GET ; Private  SET ; }
         ///  <Summary> 
        /// success
         ///  </ Summary> 
        ///  <param name = "data"> data </ param> 
        ///  <param name = "MSG"> described </ 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 = to false ; 
            Msg = MSG;
             return  the this ; 
        } 
    } 
    ///  <Summary> 
    /// Returns result
     ///  </ Summary> 
    public  static  class ResultModel 
    { 
        ///  <Summary> 
        /// success
         ///  </ Summary > 
        ///  <param name = "data"> return data </ param> 
        ///  <returns> </ returns> 
        public  static IResultModel Success <T> (T data = default (T)) 
        { 
            return  new 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 => the Failed ( " Data already exists " );
         ///  <Summary> 
        /// data does not exist
         ///  </ Summary> 
        public  static IResultModel NotExists => the Failed ( " data do not exist " ); 
    }

 

 
Add to this the middleware has been completed

 

Guess you like

Origin www.cnblogs.com/billowliu/p/12509881.html