完成错误中间件,统一返回结果

This commit is contained in:
橙子
2023-01-17 22:47:15 +08:00
parent f68ffefaa9
commit da2cf2acc5
16 changed files with 193 additions and 39 deletions

View File

@@ -0,0 +1,19 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AspNetCore.Microsoft.AspNetCore.Hosting
{
public static class StratUrlsExtensions
{
public static IWebHostBuilder UseStartUrlsServer(this IWebHostBuilder hostBuilder, IConfiguration configuration, string option = "StartUrl")
{
return hostBuilder.UseUrls(configuration.GetValue<string>(option));
}
}
}

View File

@@ -55,8 +55,9 @@ namespace Yi.Framework.Core.Extensions
//情况2 自动去找接口,如果存在就是接口,如果不存在就是本身
if (serviceType == null)
{
//获取最靠近的接口
var firstInter = type.GetInterfaces().LastOrDefault();
//获取最靠近的接口
var p = type.GetInterfaces().ToList();
var firstInter = type.GetInterfaces().Where(u => u.Name ==$"I{type.Name}").LastOrDefault();
if (firstInter is null)
{
serviceType = type;
@@ -89,7 +90,9 @@ namespace Yi.Framework.Core.Extensions
if (serviceInterfaces is not null)
{
var serviceType = type;
var firstInter = type.GetInterfaces().Where(u => u != typeof(ITransientDependency)).LastOrDefault();
//规范
var firstInter = type.GetInterfaces().Where(u => u != typeof(ITransientDependency) && u.Name == $"I{type.Name}").LastOrDefault();
if (firstInter is not null)
{
@@ -97,15 +100,15 @@ namespace Yi.Framework.Core.Extensions
}
if (serviceInterfaces.Contains(typeof(ITransientDependency)))
{
services.AddTransient(serviceType,type);
services.AddTransient(serviceType, type);
}
if (serviceInterfaces.Contains(typeof(IScopedDependency)))
{
services.AddScoped(serviceType,type);
services.AddScoped(serviceType, type);
}
if (serviceInterfaces.Contains(typeof(ISingletonDependency)))
{
services.AddSingleton(serviceType,type);
services.AddSingleton(serviceType, type);
}
}
}

View File

@@ -1,6 +1,7 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -10,6 +11,12 @@ using Yi.Framework.Core.Exceptions;
namespace Yi.Framework.Core.Extensions
{
internal class ExceptionModle
{
public string? Message { get; set; }
public string? Details { get; set; }
}
public class ErrorHandMiddleware
{
private readonly RequestDelegate _next;
@@ -22,26 +29,46 @@ namespace Yi.Framework.Core.Extensions
}
public async Task InvokeAsync(HttpContext context)
{
bool isNext = true;
try
{
await _next(context);
}
catch (BusinessException businessEx)
{
var statusCode = 200;
//业务错误,不记录
await context.Response.WriteAsync($"你好世界:友好错误,已经被中间件拦截");
context.Response.ContentType = "application/json;charset=utf-8";
context.Response.StatusCode = businessEx.Code.GetHashCode();
var result = new ExceptionModle
{
Message= businessEx.Message,
Details= businessEx.Details,
};
//业务错误,不记录日志
await context.Response.WriteAsync(JsonConvert.SerializeObject(result, new JsonSerializerSettings()
{
//设置首字母小写
ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
}));
}
catch (Exception ex)
{
isNext = false;
context.Response.ContentType = "application/json;charset=utf-8";
//系统错误,记录日志
_logger.LogError(ex, $"系统错误:{ex.Message}");
//await _errorHandle.Invoer(context, ex);
var statusCode = context.Response.StatusCode;
context.Response.StatusCode = 500;
//系统错误,需要记录
await context.Response.WriteAsync($"你好世界:系统错误,已经被中间件拦截");
var result = new ExceptionModle
{
Message = ex.Message,
Details = "系统错误",
};
await context.Response.WriteAsync(JsonConvert.SerializeObject(result, new JsonSerializerSettings()
{
//设置首字母小写
ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
}));
}
}

View File

@@ -20,8 +20,8 @@ namespace Yi.Framework.Core
//服务定位实例赋值
ServiceLocatorModel.Instance = app.ApplicationServices;
//全局错误,需要靠前
app.UseErrorHandlingServer();
//全局错误,需要靠前,放在此处无效
//app.UseErrorHandlingServer();
}
public void ConfigureServices(IServiceCollection services, ConfigureServicesContext context)

View File

@@ -1,10 +1,6 @@
using AutoMapper;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yi.Framework.Core.Model;
namespace Yi.Framework.Ddd.Services

View File

@@ -1,7 +0,0 @@
namespace Yi.Framework.Uow
{
public interface IUnitOfWorK
{
public IUnitOfWorK CreateContext();
}
}

View File

@@ -0,0 +1,94 @@
//namespace Yi.Framework.Uow
//{
// public interface IUnitOfWorkManager
// {
// SugarUnitOfWork CreateContext(bool isTran = true);
// }
// /// <summary>
// /// 这个放到实现类中
// /// </summary>
// public class SugarUnitOfWorkManager : IUnitOfWorkManager
// {
// public SugarUnitOfWorkManager(ISqlSugarClient db)
// {
// this.Db = db;
// }
// public SugarUnitOfWork Db { get; set; }
// public SugarUnitOfWork CreateContext(bool isTran = true)
// {
// return Db.CreateContext(isTran);
// }
// }
// /// <summary>
// /// 下面这个定死了
// /// </summary>
// public class SugarUnitOfWork : IDisposable
// {
// public ISqlSugarClient Db { get; internal set; }
// public ITenant Tenant { get; internal set; }
// public bool IsTran { get; internal set; }
// public bool IsCommit { get; internal set; }
// public bool IsClose { get; internal set; }
// public void Dispose()
// {
// if (this.IsTran && IsCommit == false)
// {
// this.Tenant.RollbackTran();
// }
// if (this.Db.Ado.Transaction == null && IsClose == false)
// {
// this.Db.Close();
// }
// }
// public SimpleClient<T> GetRepository<T>() where T : class, new()
// {
// TenantAttribute tenantAttribute = typeof(T).GetCustomAttribute<TenantAttribute>();
// if (tenantAttribute == null)
// {
// return new SimpleClient<T>(Db);
// }
// else
// {
// return new SimpleClient<T>(Db.AsTenant().GetConnection(tenantAttribute.configId));
// }
// }
// public RepositoryType GetMyRepository<RepositoryType>() where RepositoryType : ISugarRepository, new()
// {
// var result = new RepositoryType();
// var type = typeof(RepositoryType).GetGenericArguments()[0];
// TenantAttribute tenantAttribute = type.GetCustomAttribute<TenantAttribute>();
// if (tenantAttribute == null)
// {
// result.Context = this.Db;
// }
// else
// {
// result.Context = this.Db.AsTenant().GetConnection(tenantAttribute.configId);
// }
// return result;
// }
// public bool Commit()
// {
// if (this.IsTran && this.IsCommit == false)
// {
// this.Tenant.CommitTran();
// IsCommit = true;
// }
// if (this.Db.Ado.Transaction == null && this.IsClose == false)
// {
// this.Db.Close();
// IsClose = true;
// }
// return IsCommit;
// }
// }
//}

View File

@@ -13,14 +13,17 @@ using Yi.Framework.Ddd.Services.Abstract;
using Yi.Framework.Application.Contracts.Student.Dtos;
using Yi.Framework.Domain.Student.Entities;
using Yi.Framework.Ddd.Services;
using Yi.Framework.Core.Attributes;
namespace Yi.Framework.Application.Student
{
/// <summary>
/// 服务实现
/// </summary>
[AppService]
public class StudentService : CrudAppService<StudentEntity, StudentGetOutputDto, StudentGetListOutputDto, long, StudentGetListInputVo, StudentCreateInputVo, StudentUpdateInputVo>,
IStudentService, IAutoApiService
IStudentService,IAutoApiService
{
private readonly IStudentRepository _studentRepository;
private readonly StudentManager _studentManager;

View File

@@ -22,12 +22,10 @@ namespace Yi.Framework.Application
{
public void Configure(IApplicationBuilder app, ConfigureMiddlewareContext context)
{
}
public void ConfigureServices(IServiceCollection services, ConfigureServicesContext context)
{
services.AddTransient<IStudentService, StudentService>();
}
}
}

View File

@@ -0,0 +1 @@
global using Yi.Framework.Core.Attributes;

View File

@@ -9,6 +9,7 @@ namespace Yi.Framework.Domain.Shared.Student.ConstClasses
/// <summary>
/// 常量定义
/// </summary>
public class StudentConst
{
public const string = "失败!学生已经重复";

View File

@@ -0,0 +1 @@
global using Yi.Framework.Core.Attributes;

View File

@@ -1,3 +1,4 @@
using AspNetCore.Microsoft.AspNetCore.Hosting;
using Yi.Framework.Core.Autofac.Extensions;
using Yi.Framework.Core.Autofac.Modules;
using Yi.Framework.Core.Extensions;
@@ -6,7 +7,8 @@ using Yi.Framework.Web;
TimeTest.Start();
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.UseUrls(builder.Configuration.GetValue<string>("StartUrl"));
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>url
builder.WebHost.UseStartUrlsServer(builder.Configuration, "StartUrl");
//<2F><><EFBFBD><EFBFBD>ģ<EFBFBD><C4A3>
builder.UseYiModules(typeof(YiFrameworkWebModule));
@@ -17,10 +19,12 @@ builder.Host.ConfigureAutoFacContainer(container =>
container.RegisterYiModule(AutoFacModuleEnum.PropertiesAutowiredModule, typeof(YiFrameworkWebModule).Assembly);
});
var app = builder.Build();
var t = app.Services.GetService<Test2Entity>();
//ȫ<>ִ<EFBFBD><D6B4><EFBFBD><EFBFBD>м<EFBFBD><D0BC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ҫ<EFBFBD><D2AA><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
app.UseErrorHandlingServer();
app.MapControllers();
app.Run();

View File

@@ -1,5 +1,4 @@
using Yi.Framework.Core.Attributes;
using Yi.Framework.Core.DependencyInjection;
using Yi.Framework.Core.DependencyInjection;
namespace Yi.Framework.Web
{

View File

@@ -11,3 +11,22 @@
2023:01:17-17:45:11本次运行启动时间为4771毫秒
2023:01:17-17:45:54本次运行启动时间为1917毫秒
2023:01:17-17:48:04本次运行启动时间为2138毫秒
2023:01:17-17:57:41本次运行启动时间为1907毫秒
2023:01:17-17:58:29本次运行启动时间为1895毫秒
2023:01:17-17:58:43本次运行启动时间为1937毫秒
2023:01:17-17:59:38本次运行启动时间为1856毫秒
2023:01:17-21:06:57本次运行启动时间为2285毫秒
2023:01:17-21:09:32本次运行启动时间为2007毫秒
2023:01:17-21:10:16本次运行启动时间为1862毫秒
2023:01:17-21:12:25本次运行启动时间为2055毫秒
2023:01:17-21:13:46本次运行启动时间为5606毫秒
2023:01:17-21:14:35本次运行启动时间为4824毫秒
2023:01:17-21:18:17本次运行启动时间为8985毫秒
2023:01:17-21:19:48本次运行启动时间为1859毫秒
2023:01:17-21:21:32本次运行启动时间为1786毫秒
2023:01:17-22:41:17本次运行启动时间为1901毫秒
2023:01:17-22:42:21本次运行启动时间为1946毫秒
2023:01:17-22:42:55本次运行启动时间为1970毫秒
2023:01:17-22:43:56本次运行启动时间为2023毫秒
2023:01:17-22:45:25本次运行启动时间为1803毫秒
2023:01:17-22:45:52本次运行启动时间为1877毫秒

View File

@@ -7,11 +7,7 @@ using Yi.Framework.Sqlsugar;
namespace Yi.Framework.Web
{
/// <summary>
/// 这里是最后执行的模块
/// </summary>
[DependsOn(
typeof(YiFrameworkCoreModule),
typeof(YiFrameworkSqlsugarModule),
typeof(YiFrameworkApplicationModule)
)]