hwh
2024-07-11 982b21b945c3621e24c3e699e48a95a161bb192a
全局返回和异常处理
7个文件已修改
3个文件已删除
1个文件已添加
372 ■■■■ 已修改文件
HTML/views/SystemSettings/Job.html 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
HTML/views/SystemSettings/JobForm.html 6 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
Wms/Utility/Extension/ApiResponseActionFilter.cs 37 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
Wms/Utility/Extension/ApiResponseMiddleware.cs 97 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
Wms/Utility/Extension/LogExtends.cs 75 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
Wms/Utility/Extension/ServiceCollectionExtensions.cs 28 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
Wms/Utility/Filter/CustomerExceptionFilter.cs 54 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
Wms/Utility/Filter/CustomerExceptionMiddleware.cs 67 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
Wms/Wms/Controllers/BllTaskController.cs 1 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
Wms/Wms/Controllers/JobController.cs 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
Wms/Wms/Startup.cs 3 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
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: '添加定时任务信息',
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) {
Wms/Utility/Extension/ApiResponseActionFilter.cs
@@ -1,50 +1,52 @@
using Microsoft.AspNetCore.Http;
using 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();
        }
    }
}
Wms/Utility/Extension/ApiResponseMiddleware.cs
File was deleted
Wms/Utility/Extension/LogExtends.cs
File was deleted
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)
                // 全部日志写入到Console
                .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",
Wms/Utility/Filter/CustomerExceptionFilter.cs
New file
@@ -0,0 +1,54 @@
using 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)
                };
            }
            // 设置为true,表示异常已经被处理了
            context.ExceptionHandled = true;
            return Task.CompletedTask;
        }
    }
}
Wms/Utility/Filter/CustomerExceptionMiddleware.cs
File was deleted
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;
Wms/Wms/Controllers/JobController.cs
@@ -45,7 +45,7 @@
            {
                return "不允许过频繁执行任务!";
            }
            throw Oops.Bah("测试异常");
            return await scheduler.AddScheduleJobAsync(entity);
        }
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();