.Net Core3.0 WebApi 十二:自定義全局消息返回過濾中間件


.Net Core3.0 WebApi 目錄

.Net Core MVC理解新管道處理模型、中間件

應用場景

有的時候,接口請求會返回一些系統的狀態碼,如404,401,403等,我們會希望自定義這些返回消息,這個時候我們可以自定義一個中間件來在消息返回之前處理消息。

定義中間件

Models項目新建Errors文件夾,新建ErrorModel,定義錯誤消息返回格式。

namespace WebApi.Core.Models.Errors
{
    /// <summary>
    /// 錯誤實體
    /// </summary>
    public class ErrorModel
    {
        /// <summary>
        /// 狀態碼
        /// </summary>
        public int code { get; set; } = 500;

        /// <summary>
        /// 錯誤信息
        /// </summary>
        public string msg { get; set; }

        /// <summary>
        /// 錯誤詳情
        /// </summary>
        public string detail { get; set; }

        /// <summary>
        /// 時間戳
        /// </summary>
        public string timestamp { get; set; } = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
    }
}

Infrastructure的JsonHelper類里面新加一個方法

namespace WebApi.Core.Infrastructure.Helpers
{
    public class JsonHelper
    {
        /// <summary>
        /// 轉Json回HttpResponseMessage
        /// </summary>
        /// <param name="code"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public static string ToJson(object result)
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(result);
        }
    }
}

項目新建Middleware文件夾,新建CustomExceptionMiddleware.cs

namespace WebApi.Core.Api.Middleware
{
    public class CustomExceptionMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILoggerHelper _logger;
        public CustomExceptionMiddleware(RequestDelegate next, ILoggerHelper logger)
        {
            _next = next;
            _logger = logger;
        }
        public async Task Invoke(HttpContext httpContext)
        {
            try
            {
                await _next(httpContext);
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message, ex); // 日志記錄
                await HandleExceptionAsync(httpContext, ex.Message);
            }
            finally
            {
                var statusCode = httpContext.Response.StatusCode;
                var msg = "";
                switch (statusCode)
                {
                    case 401:
                        msg = "未授權";
                        break;
                    case 403:
                        msg = "拒絕訪問";
                        break;
                    case 404:
                        msg = "未找到服務";
                        break;
                    case 405:
                        msg = "405 Method Not Allowed";
                        break;
                    case 502:
                        msg = "請求錯誤";
                        break;
                }
                if (!string.IsNullOrWhiteSpace(msg))
                {
                    await HandleExceptionAsync(httpContext, msg);
                }
            }
        }
        ///
        private async Task HandleExceptionAsync(HttpContext httpContext, string msg)
        {
            ErrorModel error = new ErrorModel
            {
                code = httpContext.Response.StatusCode,
                msg = msg
            };
            var result = JsonHelper.ToJson(error);
            httpContext.Response.ContentType = "application/json;charset=utf-8";
            await httpContext.Response.WriteAsync(result).ConfigureAwait(false);
        }
    }

    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class CustomExceptionMiddlewareExtensions
    {
        public static IApplicationBuilder UseCustomExceptionMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<CustomExceptionMiddleware>();
        }
    }
}

使用中間件

startup.cs的Configure方法注冊中間件

app.UseCustomExceptionMiddleware();

運行項目,訪問一個需要認證的接口,可以看到消息已經是我們自定義的格式了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM