From 982b21b945c3621e24c3e699e48a95a161bb192a Mon Sep 17 00:00:00 2001
From: hwh <332078369@qq.com>
Date: 星期四, 11 七月 2024 11:12:52 +0800
Subject: [PATCH] 全局返回和异常处理

---
 /dev/null                                            |   67 ----------------
 Wms/Utility/Filter/CustomerExceptionFilter.cs        |   54 +++++++++++++
 HTML/views/SystemSettings/Job.html                   |    2 
 Wms/Utility/Extension/ApiResponseActionFilter.cs     |   37 +++++----
 Wms/Utility/Extension/ServiceCollectionExtensions.cs |   28 +++----
 Wms/Wms/Controllers/JobController.cs                 |    2 
 HTML/views/SystemSettings/JobForm.html               |    6 +
 Wms/Wms/Controllers/BllTaskController.cs             |    1 
 Wms/Wms/Startup.cs                                   |    3 
 9 files changed, 93 insertions(+), 107 deletions(-)

diff --git a/HTML/views/SystemSettings/Job.html b/HTML/views/SystemSettings/Job.html
index 4589fe9..d26a50f 100644
--- a/HTML/views/SystemSettings/Job.html
+++ b/HTML/views/SystemSettings/Job.html
@@ -329,7 +329,7 @@
 			});
 			//娣诲姞 
 			form.on('submit(LAY-app-contlist-add)', function (obj) {
-				objRowsData = {};
+				objRowsData = null;
 				layer.open({
 					type: 2,
 					title: '娣诲姞瀹氭椂浠诲姟淇℃伅',
diff --git a/HTML/views/SystemSettings/JobForm.html b/HTML/views/SystemSettings/JobForm.html
index 196337c..97707dc 100644
--- a/HTML/views/SystemSettings/JobForm.html
+++ b/HTML/views/SystemSettings/JobForm.html
@@ -210,8 +210,10 @@
 					obj.field.BeginTime = convertToDateTimeOffset(obj.field.BeginTime);
 					obj.field.EndTime = convertToDateTimeOffset(obj.field.EndTime);
 					obj.field.IntervalMilliseconds = parseInt(obj.field.IntervalMilliseconds);
-
-					obj.field.RequestType = parseInt(obj.field.RequestType);
+					if (obj.field.RequestType)
+						obj.field.RequestType = parseInt(obj.field.RequestType);
+					else
+						obj.field.RequestType = 0
 					var url = "/Job/AddJob";
 					var param;
 					if (objRowsData) {
diff --git a/Wms/Utility/Extension/ApiResponseActionFilter.cs b/Wms/Utility/Extension/ApiResponseActionFilter.cs
index 5802b58..d5afddd 100644
--- a/Wms/Utility/Extension/ApiResponseActionFilter.cs
+++ b/Wms/Utility/Extension/ApiResponseActionFilter.cs
@@ -1,50 +1,52 @@
-锘縰sing Microsoft.AspNetCore.Http;
+锘縰sing Microsoft.AspNetCore.Authentication;
+using Microsoft.AspNetCore.Http;
 using Microsoft.AspNetCore.Mvc;
 using Microsoft.AspNetCore.Mvc.Filters;
 using NetTaste;
 using Newtonsoft.Json;
 using System;
 using System.Collections.Generic;
+using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 using Utility.Entity;
-using Utility.Extension;
 
 namespace Utility
 {
-    public class ApiResponseActionFilter : IAsyncActionFilter
+    public class ApiResponseActionFilter : IAsyncResultFilter
     {
-        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
+        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
         {
-            // 鍦ㄦ墽琛屽姩浣滀箣鍓嶇殑閫昏緫
-            var resultContext = await next(); // 鎵ц鍔ㄤ綔鏂规硶骞惰幏鍙栨墽琛岀粨鏋�
-
-            // 鍦ㄦ墽琛屽姩浣滀箣鍚庣殑閫昏緫
-            if (resultContext.Result is ObjectResult objectResult)
+            if (context.Result is ObjectResult objectResult)
             {
+                if (objectResult.StatusCode != null)
+                {
+                    await next();
+                    return;
+                }
                 ApiResponse<object> apiResponse;
                 if (objectResult.Value is SqlSugarPagedList)
                 {
                     apiResponse = new ApiResponse<object>(
-                    context.HttpContext.Response.StatusCode == 200 ? 0 : 1,
-                    context.HttpContext.Response.StatusCode == 200 ? "璇锋眰鎴愬姛" : "閿欒",
+                    0, "璇锋眰鎴愬姛",
                     ((SqlSugarPagedList)objectResult.Value).Items,
                     ((SqlSugarPagedList)objectResult.Value).Total);
                 }
                 else
                 {
                     apiResponse = new ApiResponse<object>(
-                    context.HttpContext.Response.StatusCode == 200 ? 0 : 1,
-                    context.HttpContext.Response.StatusCode == 200 ? "璇锋眰鎴愬姛" : "閿欒",
+                    0, "璇锋眰鎴愬姛",
                     objectResult.Value);
                 }
                 var json = JsonConvert.SerializeObject(apiResponse);
                 context.HttpContext.Response.ContentType = "application/json";
                 context.HttpContext.Response.ContentLength = Encoding.UTF8.GetByteCount(json);
 
-                await context.HttpContext.Response.WriteAsync(json);
+                context.Result = new ObjectResult(apiResponse);
+                //await context.HttpContext.Response.WriteAsync(json);
+
             }
-            if (resultContext.Result is EmptyResult)
+            else if (context.Result is EmptyResult)
             {
                 var apiResponse = new ApiResponse<object>(
                     context.HttpContext.Response.StatusCode == 200 ? 0 : 1,
@@ -55,9 +57,10 @@
                 var json = JsonConvert.SerializeObject(apiResponse);
                 context.HttpContext.Response.ContentType = "application/json";
                 context.HttpContext.Response.ContentLength = Encoding.UTF8.GetByteCount(json);
-
-                await context.HttpContext.Response.WriteAsync(json);
+                context.Result = new ObjectResult(apiResponse);
+                //await context.HttpContext.Response.WriteAsync(json);
             }
+            await next();
         }
     }
 }
diff --git a/Wms/Utility/Extension/ApiResponseMiddleware.cs b/Wms/Utility/Extension/ApiResponseMiddleware.cs
deleted file mode 100644
index 745862c..0000000
--- a/Wms/Utility/Extension/ApiResponseMiddleware.cs
+++ /dev/null
@@ -1,97 +0,0 @@
-锘縰sing Microsoft.AspNetCore.Builder;
-using Microsoft.AspNetCore.Http;
-using Microsoft.AspNetCore.Mvc.Controllers;
-using Newtonsoft.Json;
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using Utility.Entity;
-
-namespace Utility.Extension
-{
-    public class ApiResponseMiddleware : IMiddleware
-    {
-        public ApiResponseMiddleware()
-        {
-
-        }
-
-        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
-        {
-            if (ShouldApplyApiResponseMiddleware(context))
-            {
-                // 鎹曡幏鍝嶅簲
-                var originalBodyStream = context.Response.Body;
-
-                using (var responseBody = new MemoryStream())
-                {
-                    context.Response.Body = responseBody;
-
-                    await next(context);
-                    // 璇诲彇鍝嶅簲鍐呭
-                    context.Response.Body.Seek(0, SeekOrigin.Begin);
-                    var body = await new StreamReader(context.Response.Body).ReadToEndAsync();
-                    context.Response.Body.Seek(0, SeekOrigin.Begin);
-
-                    // 鍙嶅簭鍒楀寲鍝嶅簲鍐呭
-                    object data = null;
-                    if (!string.IsNullOrEmpty(body))
-                    {
-                        try
-                        {
-                            data = JsonConvert.DeserializeObject<object>(body);
-                        }
-                        catch (JsonException)
-                        {
-                            // 濡傛灉鍝嶅簲涓嶆槸鏈夋晥鐨凧SON鏍煎紡锛岀洿鎺ュ皢鍏朵綔涓哄瓧绗︿覆鏁版嵁澶勭悊
-                            data = body;
-                        }
-                    }
-
-                    var apiResponse = new ApiResponse<object>(
-                        code: context.Response.StatusCode == StatusCodes.Status200OK ? (int)ResponseEnum.Sucess : (int)ResponseEnum.Fail,
-                        message: context.Response.StatusCode == StatusCodes.Status200OK ? "璇锋眰鎴愬姛" : "",
-                        data: data
-                    );
-
-                    var json = JsonConvert.SerializeObject(apiResponse);
-                    context.Response.ContentType = "application/json";
-                    context.Response.ContentLength = Encoding.UTF8.GetByteCount(json);
-
-                    context.Response.Body = originalBodyStream;
-                    await context.Response.WriteAsync(json);
-                }
-            }
-            else
-            {
-                await next(context);
-            }
-        }
-        private bool ShouldApplyApiResponseMiddleware(HttpContext context)
-        {
-            // 鑾峰彇褰撳墠澶勭悊璇锋眰鐨勬帶鍒跺櫒淇℃伅
-            var controllerActionDescriptor = context.GetEndpoint()?.Metadata.GetMetadata<ControllerActionDescriptor>();
-            if (controllerActionDescriptor != null)
-            {
-                // 鍒ゆ柇鎺у埗鍣ㄦ槸鍚﹀甫鏈� ResponseAttribute 鐗规��
-                return controllerActionDescriptor.ControllerTypeInfo.IsDefined(typeof(UnifyResponseAttribute), inherit: true);
-            }
-            return false;
-        }
-    }
-    public static class ApiResponse
-    {
-        public static void UseApiResponse(this IApplicationBuilder app)
-        {
-            app.UseMiddleware<ApiResponseMiddleware>();
-        }
-    }
-
-    public class UnifyResponseAttribute : Attribute
-    {
-
-    }
-}
diff --git a/Wms/Utility/Extension/LogExtends.cs b/Wms/Utility/Extension/LogExtends.cs
deleted file mode 100644
index de01c02..0000000
--- a/Wms/Utility/Extension/LogExtends.cs
+++ /dev/null
@@ -1,75 +0,0 @@
-锘縰sing Serilog.Events;
-using Serilog;
-using System;
-using System.Collections.Generic;
-using System.Text;
-using Microsoft.Extensions.DependencyInjection;
-using Microsoft.Extensions.Logging;
-
-namespace Wms
-{
-    public static class LogExtends
-    {
-        //const string infoPath = "Logs/Information.log";
-        //const string warnPath = "Logs/Warning.log";
-        //const string errorPath = "Logs/Error.log";
-        //const string fatalPath = "Logs/Fatal.log";
-        //const string template = "鏃堕棿: {Timestamp:yyyy-MM-dd HH:mm:ss}{NewLine}鏉ユ簮: {SourceContext}{NewLine}鍐呭: [{Level:u3}] {Message}{NewLine}{Exception}{NewLine}";
-
-        //// 鍙互灏嗘棩蹇楄緭鍑哄埌鎺у埗鍙般�佹枃浠躲�佹暟鎹簱銆丒S绛�
-        //public static void AddSerilog(this IServiceCollection c)
-        //{
-        //    Log.Logger = new LoggerConfiguration()
-        //        .MinimumLevel.Information()
-        //        .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) // 鎺掗櫎Dotnet鑷甫鐨勬棩蹇�
-        //        .Enrich.FromLogContext()
-        //        .WriteTo.Console(outputTemplate: template)
-        //        .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(lev => lev.Level == LogEventLevel.Information).WriteTo.Async(congfig => congfig.File(
-        //                infoPath,
-        //                rollingInterval: RollingInterval.Day,
-        //                fileSizeLimitBytes: 1024 * 1024 * 10,    //榛樿1GB
-        //                retainedFileCountLimit: 100,                   //淇濈暀鏈�杩戝灏戜釜鏂囦欢,榛樿31涓�
-        //                rollOnFileSizeLimit: true,                       //瓒呰繃鏂囦欢澶у皬鏃�,鑷姩鍒涘缓鏂版枃浠�  
-        //                shared: true,
-        //                outputTemplate: template)
-        //            ))
-
-        //        .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(lev => lev.Level == LogEventLevel.Warning).WriteTo.Async(congfig => congfig.File(
-        //                warnPath,
-        //                rollingInterval: RollingInterval.Day,
-        //                fileSizeLimitBytes: 1024 * 1024 * 10,
-        //                retainedFileCountLimit: 100,
-        //                rollOnFileSizeLimit: true,
-        //                shared: true,
-        //                outputTemplate: template)
-        //        ))
-
-        //        .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(lev => lev.Level == LogEventLevel.Error).WriteTo.Async(congfig => congfig.File(
-        //                errorPath,
-        //                rollingInterval: RollingInterval.Day,
-        //                fileSizeLimitBytes: 1024 * 1024 * 10,
-        //                retainedFileCountLimit: 100,
-        //                rollOnFileSizeLimit: true,
-        //                shared: true,
-        //                outputTemplate: template)
-        //        ))
-
-        //        .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(lev => lev.Level == LogEventLevel.Fatal).WriteTo.Async(congfig => congfig.File(
-        //                fatalPath,
-        //                rollingInterval: RollingInterval.Day,
-        //                fileSizeLimitBytes: 1024 * 1024 * 10,
-        //                retainedFileCountLimit: 100,
-        //                rollOnFileSizeLimit: true,
-        //                shared: true,
-        //                outputTemplate: template)
-        //        )).CreateLogger();
-
-        //    // 娉ㄥ叆鍒板鍣�
-        //    c.AddLogging(opt =>
-        //    {
-        //        opt.ClearProviders();
-        //        opt.AddSerilog(dispose: true);
-        //    });
-        //}
-    }
-}
diff --git a/Wms/Utility/Extension/ServiceCollectionExtensions.cs b/Wms/Utility/Extension/ServiceCollectionExtensions.cs
index 2669a82..0abe4ed 100644
--- a/Wms/Utility/Extension/ServiceCollectionExtensions.cs
+++ b/Wms/Utility/Extension/ServiceCollectionExtensions.cs
@@ -24,19 +24,23 @@
             // 鍒涘缓Serilog璁板綍鏃ュ織
             Log.Logger = new LoggerConfiguration()
                 .MinimumLevel.Information()
-                .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) // 鎺掗櫎Dotnet鑷甫鐨勬棩蹇�
-                //.MinimumLevel.Verbose()
-                //.MinimumLevel.Override("System", LogEventLevel.Debug)
-                //.MinimumLevel.Override("Microsoft", LogEventLevel.Debug)
-                //.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Error)
-                //.MinimumLevel.Override("Microsoft.AspNetCore.Cors.Infrastructure.CorsService", LogEventLevel.Error)
-                //.MinimumLevel.Override("Microsoft.AspNetCore.Mvc", LogEventLevel.Error)
-                //.MinimumLevel.Override("Microsoft.AspNetCore.Hosting", LogEventLevel.Error)
+                .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
+                .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Fatal)
+                .MinimumLevel.Override("Quartz", LogEventLevel.Warning)
+                .MinimumLevel.Override("Serilog", LogEventLevel.Information)
                 // 鍏ㄩ儴鏃ュ織鍐欏叆鍒癈onsole
                 .WriteTo.Console()
                 .WriteTo.Async(c => c.Console(
                    theme: AnsiConsoleTheme.Literate,
                     outputTemplate: template))
+                // Debug鏃ュ織鍐欏叆鍒版枃浠�
+                //.WriteTo.Async(c => c.File(
+                //    path: "Logs/Debug_.txt",
+                //    rollingInterval: RollingInterval.Day,
+                //    fileSizeLimitBytes: 1024 * 1024 * 10,
+                //    retainedFileCountLimit: 100,
+                //    outputTemplate: template,
+                //    restrictedToMinimumLevel: LogEventLevel.Debug))
                 // Information鏃ュ織鍐欏叆鍒版枃浠�
                 .WriteTo.Async(c => c.File(
                     path: "Logs/Information_.txt",
@@ -45,14 +49,6 @@
                     retainedFileCountLimit: 100,
                     outputTemplate: template,
                     restrictedToMinimumLevel: LogEventLevel.Information))
-                // Debug鏃ュ織鍐欏叆鍒版枃浠�
-                .WriteTo.Async(c => c.File(
-                    path: "Logs/Verbose.txt",
-                    rollingInterval: RollingInterval.Day,
-                    fileSizeLimitBytes: 1024 * 1024 * 10,
-                    retainedFileCountLimit: 100,
-                    outputTemplate: template,
-                    restrictedToMinimumLevel: LogEventLevel.Verbose))
                 // Warning鏃ュ織鍐欏叆鍒版枃浠�
                 .WriteTo.Async(c => c.File(
                     path: "Logs/Warning_.txt",
diff --git a/Wms/Utility/Filter/CustomerExceptionFilter.cs b/Wms/Utility/Filter/CustomerExceptionFilter.cs
new file mode 100644
index 0000000..2c2c54d
--- /dev/null
+++ b/Wms/Utility/Filter/CustomerExceptionFilter.cs
@@ -0,0 +1,54 @@
+锘縰sing Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.Mvc.Filters;
+using Microsoft.Extensions.Logging;
+using Newtonsoft.Json;
+using System;
+using System.Collections.Generic;
+using System.Text;
+using System.Threading.Tasks;
+using Utility.Entity;
+
+namespace Utility
+{
+    public class CustomerExceptionFilter : IAsyncExceptionFilter
+    {
+        /// <summary>
+        /// 閲嶅啓OnExceptionAsync鏂规硶锛屽畾涔夎嚜宸辩殑澶勭悊閫昏緫
+        /// </summary>
+        /// <param name="context"></param>
+        /// <returns></returns>
+        private readonly ILogger<CustomerExceptionFilter> _logger;
+        public CustomerExceptionFilter(ILogger<CustomerExceptionFilter> logger)
+        {
+            _logger = logger;
+        }
+        public Task OnExceptionAsync(ExceptionContext context)
+        {
+            // 濡傛灉寮傚父娌℃湁琚鐞嗗垯杩涜澶勭悊
+            if (context.ExceptionHandled == false)
+            {
+                var result = "绯荤粺寮傚父锛岃鑱旂郴绠$悊鍛�";
+                if (context.Exception is AppFriendlyException)
+                    result = context.Exception.Message;
+                var apiResponse = new ApiResponse<object>(
+                        code: (int)ResponseEnum.Error,
+                        message: result,
+                        data: result
+                    );
+                _logger.LogError(context.Exception, context.Exception.Message);
+                context.Result = new ContentResult
+                {
+                    // 杩斿洖鐘舵�佺爜璁剧疆涓�200锛岃〃绀烘垚鍔�
+                    StatusCode = StatusCodes.Status200OK,
+                    // 璁剧疆杩斿洖鏍煎紡
+                    ContentType = "application/json;charset=utf-8",
+                    Content = JsonConvert.SerializeObject(apiResponse)
+                };
+            }
+            // 璁剧疆涓簍rue锛岃〃绀哄紓甯稿凡缁忚澶勭悊浜�
+            context.ExceptionHandled = true;
+            return Task.CompletedTask;
+        }
+    }
+}
diff --git a/Wms/Utility/Filter/CustomerExceptionMiddleware.cs b/Wms/Utility/Filter/CustomerExceptionMiddleware.cs
deleted file mode 100644
index 33fe7af..0000000
--- a/Wms/Utility/Filter/CustomerExceptionMiddleware.cs
+++ /dev/null
@@ -1,67 +0,0 @@
-锘縰sing Microsoft.AspNetCore.Http;
-using Microsoft.AspNetCore.Mvc;
-using System.Threading.Tasks;
-using System;
-using System.Text.Json;
-using Microsoft.AspNetCore.Builder;
-using Microsoft.Extensions.Logging;
-using Utility.Entity;
-using Newtonsoft.Json;
-using System.Text;
-
-namespace Utility
-{
-    public class CustomerExceptionMiddleware
-    {
-        private readonly RequestDelegate _next;
-        private readonly ILogger<CustomerExceptionMiddleware> _logger;
-
-        public CustomerExceptionMiddleware(RequestDelegate next, ILogger<CustomerExceptionMiddleware> logger)
-        {
-            _next = next;
-            _logger = logger;
-        }
-
-        public async Task Invoke(HttpContext context)
-        {
-            try
-            {
-                await _next(context);
-            }
-            catch (Exception ex)
-            {
-                _logger.LogError(ex, ex.Message);
-                context.Response.ContentType = "application/json";
-                context.Response.StatusCode = StatusCodes.Status500InternalServerError;
-                var result = "绯荤粺寮傚父锛岃鑱旂郴绠$悊鍛�";
-                if (ex is AppFriendlyException)
-                    result = ex.Message;
-                var apiResponse = new ApiResponse<object>(
-                        code: (int)ResponseEnum.Error,
-                        message: result,
-                        data: result
-                    );
-                var json = JsonConvert.SerializeObject(apiResponse);
-                context.Response.ContentType = "application/json";
-                context.Response.ContentLength = Encoding.UTF8.GetByteCount(json);
-                await context.Response.WriteAsync(json);
-            }
-        }
-    }
-
-    /// <summary>
-    /// 闈欐�佺被
-    /// </summary>
-    public static class ExceptionMiddlewareExtension
-    {
-        /// <summary>
-        /// 闈欐�佹柟娉�
-        /// </summary>
-        /// <param name="app">瑕佽繘琛屾墿灞曠殑绫诲瀷</param>
-        public static void UseExceptionMiddleware(this IApplicationBuilder app)
-        {
-            app.UseMiddleware(typeof(CustomerExceptionMiddleware));
-        }
-    }
-}
-
diff --git a/Wms/Wms/Controllers/BllTaskController.cs b/Wms/Wms/Controllers/BllTaskController.cs
index 7e95e77..39dea63 100644
--- a/Wms/Wms/Controllers/BllTaskController.cs
+++ b/Wms/Wms/Controllers/BllTaskController.cs
@@ -8,7 +8,6 @@
 using System.Security.Claims;
 using System.Threading.Tasks;
 using Utility;
-using Utility.Extension;
 using Wms.Tools;
 using WMS.IBLL.IBllTaskServer;
 
diff --git a/Wms/Wms/Controllers/JobController.cs b/Wms/Wms/Controllers/JobController.cs
index 6b1f28f..f35990d 100644
--- a/Wms/Wms/Controllers/JobController.cs
+++ b/Wms/Wms/Controllers/JobController.cs
@@ -45,7 +45,7 @@
             {
                 return "涓嶅厑璁歌繃棰戠箒鎵ц浠诲姟锛�";
             }
-
+            throw Oops.Bah("娴嬭瘯寮傚父");
             return await scheduler.AddScheduleJobAsync(entity);
         }
 
diff --git a/Wms/Wms/Startup.cs b/Wms/Wms/Startup.cs
index 694afba..8b90be5 100644
--- a/Wms/Wms/Startup.cs
+++ b/Wms/Wms/Startup.cs
@@ -17,7 +17,6 @@
 using Serilog;
 using Autofac.Core;
 using Utility;
-using Utility.Extension;
 using Microsoft.Extensions.Options;
 using Microsoft.AspNetCore.Http;
 using SqlSugar;
@@ -48,6 +47,7 @@
             services.AddControllers(options =>
             {
                 options.Filters.Add<RequestAuditLogFilter>();
+                options.Filters.Add<CustomerExceptionFilter>();
             })
                 .AddJsonOptions(options =>
                     {
@@ -164,7 +164,6 @@
             }
             //全局返回规范
             //app.UseApiResponse();//弃用 改用Filter [ServiceFilter(typeof(ApiResponseActionFilter))]
-            app.UseExceptionMiddleware();
 
             //使用Serilog记录请求日志
             app.UseSerilogRequestLogging();

--
Gitblit v1.8.0