diff --git a/IRaCIS.Core.API/Controllers/ErrorController.cs b/IRaCIS.Core.API/Controllers/ErrorController.cs index c273d3e55..92cbd2b1d 100644 --- a/IRaCIS.Core.API/Controllers/ErrorController.cs +++ b/IRaCIS.Core.API/Controllers/ErrorController.cs @@ -25,12 +25,12 @@ namespace EasyCaching.Demo.Interceptors.Controllers { ControllerContext.HttpContext.Response.StatusCode = 401; } - + return ResponseOutput.NotOk($"Client error, actual request error status code({code})"); } else { - + return ResponseOutput.NotOk($"Server error , actual request error status code({code})"); } diff --git a/IRaCIS.Core.API/Controllers/ExtraController.cs b/IRaCIS.Core.API/Controllers/ExtraController.cs index 717b3208d..d6f98687c 100644 --- a/IRaCIS.Core.API/Controllers/ExtraController.cs +++ b/IRaCIS.Core.API/Controllers/ExtraController.cs @@ -1,43 +1,27 @@ -using System; -using System.Net.Http; -using IRaCIS.Application.Interfaces; +using Amazon.SecurityToken; using IRaCIS.Application.Contracts; +using IRaCIS.Application.Interfaces; using IRaCIS.Core.Application.Auth; -using IRaCIS.Core.Application.Filter; -using IRaCIS.Core.Domain.Share; -using IRaCIS.Core.Infrastructure.Extention; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Configuration; -using System.Collections.Generic; -using System.Text; -using Microsoft.AspNetCore.Http; -using IRaCIS.Core.Application.Interfaces; -using System.Threading.Tasks; -using IRaCIS.Core.Application.Service; -using IRaCIS.Core.Infra.EFCore; -using IRaCIS.Core.Domain.Models; -using IRaCIS.Core.Infrastructure; -using System.Linq; -using Microsoft.Extensions.Logging; -using MassTransit; -using Microsoft.AspNetCore.Hosting; -using IRaCIS.Core.Application.Helper; -using Microsoft.Extensions.Options; using IRaCIS.Core.Application.Contracts; -using LoginReturnDTO = IRaCIS.Application.Contracts.LoginReturnDTO; -using DocumentFormat.OpenXml.Spreadsheet; -using AutoMapper.QueryableExtensions; -using NetTopologySuite.Algorithm; +using IRaCIS.Core.Application.Helper; +using IRaCIS.Core.Application.Service; +using IRaCIS.Core.Domain.Models; +using IRaCIS.Core.Domain.Share; +using IRaCIS.Core.Infra.EFCore; +using IRaCIS.Core.Infrastructure.Extention; +using MassTransit; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using System; +using System.Linq; +using System.Text; +using System.Threading.Tasks; using ZiggyCreatures.Caching.Fusion; -using AlibabaCloud.SDK.Sts20150401; -using AlibabaCloud.SDK.Sts20150401.Models; -using Org.BouncyCastle.Tls; -using Amazon.SecurityToken.Model; -using Amazon.SecurityToken; -using Amazon; using AssumeRoleRequest = Amazon.SecurityToken.Model.AssumeRoleRequest; -using AutoMapper; +using LoginReturnDTO = IRaCIS.Application.Contracts.LoginReturnDTO; namespace IRaCIS.Api.Controllers { diff --git a/IRaCIS.Core.API/Controllers/FinancialChangeController.cs b/IRaCIS.Core.API/Controllers/FinancialChangeController.cs index 40ca6fc59..d64215b8e 100644 --- a/IRaCIS.Core.API/Controllers/FinancialChangeController.cs +++ b/IRaCIS.Core.API/Controllers/FinancialChangeController.cs @@ -1,18 +1,17 @@ -using Microsoft.AspNetCore.Mvc; -using System; -using System.Collections.Generic; +using IRaCIS.Application.Contracts; using IRaCIS.Application.Interfaces; -using IRaCIS.Application.Contracts; using IRaCIS.Core.Application.Filter; -using IRaCIS.Core.Infrastructure.Extention; -using Microsoft.AspNetCore.Authorization; -using System.Threading.Tasks; using IRaCIS.Core.Application.Service; using IRaCIS.Core.Application.Service.Inspection.DTO; -using IRaCIS.Core.Infra.EFCore; using IRaCIS.Core.Domain.Models; -using IRaCIS.Core.Application.Auth; +using IRaCIS.Core.Infra.EFCore; +using IRaCIS.Core.Infrastructure.Extention; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Localization; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; namespace IRaCIS.Core.API.Controllers.Special { @@ -24,7 +23,7 @@ namespace IRaCIS.Core.API.Controllers.Special ICalculateService _calculateService, IStringLocalizer _localizer) : ControllerBase { - + //[TrialAudit(AuditType.TrialAudit, AuditOptType.AddOrUpdateTrial)] @@ -36,8 +35,8 @@ namespace IRaCIS.Core.API.Controllers.Special public async Task AddOrUpdateTrialInspection(DataInspectionDto opt) { - var fun =await AddOrUpdateTrial(opt.Data); - + var fun = await AddOrUpdateTrial(opt.Data); + return fun; } @@ -49,7 +48,7 @@ namespace IRaCIS.Core.API.Controllers.Special //[Authorize(Policy = IRaCISPolicy.PM_APM)] [TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AddOrUpdateTrial", "BeforeOngoingCantOpt", "AfterStopCannNotOpt" })] - public async Task> AddOrUpdateTrial(TrialCommand param) + public async Task> AddOrUpdateTrial(TrialCommand param) { var userId = Guid.Parse(User.FindFirst("id").Value); var result = await _trialService.AddOrUpdateTrial(param); @@ -86,9 +85,9 @@ namespace IRaCIS.Core.API.Controllers.Special /// /// /// - + [HttpPost, Route("doctorWorkload/workLoadAddOrUpdate")] - [TypeFilter(typeof(TrialResourceFilter),Arguments = new object[] { "AfterStopCannNotOpt" })] + [TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })] public async Task WorkLoadAddOrUpdate([FromServices] IDoctorWorkloadService _trialWorkloadService, WorkloadCommand workLoadAddOrUpdateModel) { var userId = Guid.Parse(User.FindFirst("id").Value); @@ -108,9 +107,9 @@ namespace IRaCIS.Core.API.Controllers.Special } - + [HttpDelete, Route("doctorWorkload/deleteWorkLoad/{id:guid}/{trialId:guid}")] - [TypeFilter(typeof(TrialResourceFilter),Arguments = new object[] { "AfterStopCannNotOpt" })] + [TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })] public async Task DeleteWorkLoad([FromServices] IDoctorWorkloadService _trialWorkloadService, Guid id) { //先判断该工作量的费用是否被锁定,如果被锁定,则不能删除 @@ -143,7 +142,7 @@ namespace IRaCIS.Core.API.Controllers.Special /// /// 添加或更新汇率(会触发没有对锁定的费用计算) /// - + [HttpPost, Route("exchangeRate/addOrUpdateExchangeRate")] public async Task AddOrUpdateExchangeRate([FromServices] IExchangeRateService _exchangeRateService, [FromServices] IPaymentAdjustmentService _costAdjustmentService, ExchangeRateCommand addOrUpdateModel) { @@ -153,7 +152,7 @@ namespace IRaCIS.Core.API.Controllers.Special { if (item != null) { - await _calculateService.CalculateMonthlyPayment(new CalculateDoctorAndMonthDTO() + await _calculateService.CalculateMonthlyPayment(new CalculateDoctorAndMonthDTO() { NeedCalculateReviewers = new List() { @@ -163,7 +162,7 @@ namespace IRaCIS.Core.API.Controllers.Special }, User.FindFirst("id").Value); } } - await _costAdjustmentService.CalculateCNY(addOrUpdateModel.YearMonth, addOrUpdateModel.Rate); + await _costAdjustmentService.CalculateCNY(addOrUpdateModel.YearMonth, addOrUpdateModel.Rate); return result; } @@ -171,13 +170,13 @@ namespace IRaCIS.Core.API.Controllers.Special /// /// 添加或更新 职称单价[AUTH] /// - + [HttpPost, Route("rankPrice/addOrUpdateRankPrice")] public async Task AddOrUpdateRankPrice([FromServices] IReviewerPayInfoService _reviewerPayInfoService, [FromServices] IRankPriceService _rankPriceService, RankPriceCommand addOrUpdateModel) { if (addOrUpdateModel.Id != Guid.Empty && addOrUpdateModel.Id != null) { - var needCalReviewerIds =await _reviewerPayInfoService.GetReviewerIdByRankId(Guid.Parse(addOrUpdateModel.Id.ToString())); + var needCalReviewerIds = await _reviewerPayInfoService.GetReviewerIdByRankId(Guid.Parse(addOrUpdateModel.Id.ToString())); var calcList = await _calculateService.GetNeedCalculateReviewerList(Guid.Empty, string.Empty); foreach (var item in calcList) @@ -204,12 +203,12 @@ namespace IRaCIS.Core.API.Controllers.Special /// /// 添加或更新(替换)医生支付展信息[AUTH] /// - + [HttpPost, Route("reviewerPayInfo/addOrUpdateReviewerPayInfo")] public async Task AddOrUpdateReviewerPayInfo([FromServices] IReviewerPayInfoService _doctorPayInfoService, ReviewerPayInfoCommand addOrUpdateModel) { var userId = Guid.Parse(User.FindFirst("id").Value); - var result =await _doctorPayInfoService.AddOrUpdateReviewerPayInfo(addOrUpdateModel, userId); + var result = await _doctorPayInfoService.AddOrUpdateReviewerPayInfo(addOrUpdateModel, userId); var calcList = await _calculateService.GetNeedCalculateReviewerList(addOrUpdateModel.DoctorId, string.Empty); foreach (var item in calcList) { @@ -233,12 +232,12 @@ namespace IRaCIS.Core.API.Controllers.Special /// /// 保存(替换)项目支付价格信息(会触发没有被锁定的费用计算)[AUTH] /// - + [HttpPost, Route("trialPaymentPrice/addOrUpdateTrialPaymentPrice")] public async Task AddOrUpdateTrialPaymentPrice([FromServices] ITrialPaymentPriceService _trialPaymentPriceService, TrialPaymentPriceCommand addOrUpdateModel) { var userId = Guid.Parse(User.FindFirst("id").Value); - var result =await _trialPaymentPriceService.AddOrUpdateTrialPaymentPrice(addOrUpdateModel); + var result = await _trialPaymentPriceService.AddOrUpdateTrialPaymentPrice(addOrUpdateModel); var needCalReviewerIds = await _trialService.GetTrialEnrollmentReviewerIds(addOrUpdateModel.TrialId); var calcList = await _calculateService.GetNeedCalculateReviewerList(Guid.Empty, string.Empty); @@ -246,7 +245,7 @@ namespace IRaCIS.Core.API.Controllers.Special { if (item != null && needCalReviewerIds.Contains(item.DoctorId)) { - await _calculateService.CalculateMonthlyPayment(new CalculateDoctorAndMonthDTO() + await _calculateService.CalculateMonthlyPayment(new CalculateDoctorAndMonthDTO() { NeedCalculateReviewers = new List() { @@ -262,12 +261,12 @@ namespace IRaCIS.Core.API.Controllers.Special /// /// 批量更新奖励费用[AUTH] /// - + [HttpPost, Route("volumeReward/addOrUpdatevolumeRewardPriceList")] public async Task AddOrUpdateAwardPriceList([FromServices] IVolumeRewardService _volumeRewardService, IEnumerable addOrUpdateModel) { - var result =await _volumeRewardService.AddOrUpdateVolumeRewardPriceList(addOrUpdateModel); + var result = await _volumeRewardService.AddOrUpdateVolumeRewardPriceList(addOrUpdateModel); var calcList = await _calculateService.GetNeedCalculateReviewerList(Guid.Empty, string.Empty); foreach (var item in calcList) diff --git a/IRaCIS.Core.API/Controllers/InspectionController.cs b/IRaCIS.Core.API/Controllers/InspectionController.cs index 26c8ba83e..3e2855043 100644 --- a/IRaCIS.Core.API/Controllers/InspectionController.cs +++ b/IRaCIS.Core.API/Controllers/InspectionController.cs @@ -1,24 +1,18 @@  -using System.Threading.Tasks; -using AutoMapper; - using IRaCIS.Application.Interfaces; using IRaCIS.Core.Application.Contracts; using IRaCIS.Core.Application.Filter; using IRaCIS.Core.Application.Image.QA; -using IRaCIS.Core.Application.Interfaces; using IRaCIS.Core.Application.Service; using IRaCIS.Core.Application.Service.Inspection.DTO; using IRaCIS.Core.Application.Service.Inspection.Interface; using IRaCIS.Core.Application.Service.Reading.Dto; using IRaCIS.Core.Application.Service.Reading.Interface; using IRaCIS.Core.Application.ViewModel; -using IRaCIS.Core.Domain.Models; -using IRaCIS.Core.Domain.Share; using IRaCIS.Core.Infra.EFCore; using IRaCIS.Core.Infrastructure.Extention; -using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; +using System.Threading.Tasks; namespace IRaCIS.Core.API.Controllers @@ -38,7 +32,7 @@ namespace IRaCIS.Core.API.Controllers IReadingMedicineQuestionService _readingMedicineQuestionService ) : ControllerBase { - + #region 获取稽查数据 /// /// 获取稽查数据 @@ -117,7 +111,7 @@ namespace IRaCIS.Core.API.Controllers [UnitOfWork] public async Task TrialReadingInfoSign(DataInspectionDto opt) { - + var singid = await _inspectionService.RecordSing(opt.SignInfo); var result = await _trialConfigService.TrialReadingInfoSign(opt.Data); await _inspectionService.CompletedSign(singid, result); @@ -313,7 +307,7 @@ namespace IRaCIS.Core.API.Controllers { opt.Data.IsTrialBasicLogicConfirmed = true; - var singid= await _inspectionService.RecordSing(opt.SignInfo); + var singid = await _inspectionService.RecordSing(opt.SignInfo); var result = await _trialConfigService.ConfigTrialBasicInfo(opt.Data); await _inspectionService.CompletedSign(singid, result); return result; @@ -340,7 +334,7 @@ namespace IRaCIS.Core.API.Controllers } - + /// @@ -355,7 +349,7 @@ namespace IRaCIS.Core.API.Controllers { opt.Data.IsTrialUrgentConfirmed = true; var singid = await _inspectionService.RecordSing(opt.SignInfo); - var result= await _trialConfigService.ConfigTrialUrgentInfo(opt.Data); + var result = await _trialConfigService.ConfigTrialUrgentInfo(opt.Data); await _inspectionService.CompletedSign(singid, result); return result; } @@ -379,7 +373,7 @@ namespace IRaCIS.Core.API.Controllers /// [HttpPost, Route("Inspection/configTrialBasicInfo/TrialConfigSignatureConfirm")] [UnitOfWork] - [TypeFilter(typeof(TrialResourceFilter),Arguments = new object[] { "AfterStopCannNotOpt" })] + [TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })] public async Task TrialConfigSignatureConfirm(DataInspectionDto opt) { @@ -390,30 +384,30 @@ namespace IRaCIS.Core.API.Controllers } - /// - /// 重置并同步项目阅片标准 - /// - /// - [HttpPost, Route("Inspection/ReadingCriterion/ResetAndAsyncCriterion")] - [UnitOfWork] - [TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })] + /// + /// 重置并同步项目阅片标准 + /// + /// + [HttpPost, Route("Inspection/ReadingCriterion/ResetAndAsyncCriterion")] + [UnitOfWork] + [TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })] - public async Task ResetAndAsyncCriterion(DataInspectionDto opt) - { - var singid = await _inspectionService.RecordSing(opt.SignInfo); - var result = await _trialConfigService.ResetAndAsyncCriterion(opt.Data); - await _inspectionService.CompletedSign(singid, result); - return result; - } + public async Task ResetAndAsyncCriterion(DataInspectionDto opt) + { + var singid = await _inspectionService.RecordSing(opt.SignInfo); + var result = await _trialConfigService.ResetAndAsyncCriterion(opt.Data); + await _inspectionService.CompletedSign(singid, result); + return result; + } - /// - /// CRC RequestToQC 批量提交 - /// - /// - /// - [HttpPost, Route("Inspection/QCOperation/CRCRequestToQC")] + /// + /// CRC RequestToQC 批量提交 + /// + /// + /// + [HttpPost, Route("Inspection/QCOperation/CRCRequestToQC")] [TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })] [UnitOfWork] public async Task CRCRequestToQC(DataInspectionDto opt) @@ -434,7 +428,7 @@ namespace IRaCIS.Core.API.Controllers public async Task QCPassedOrFailed(DataInspectionDto opt) { var singid = await _inspectionService.RecordSing(opt.SignInfo); - var result= await _qCOperationService.QCPassedOrFailed(opt.Data.trialId, opt.Data.subjectVisitId, opt.Data.auditState); + var result = await _qCOperationService.QCPassedOrFailed(opt.Data.trialId, opt.Data.subjectVisitId, opt.Data.auditState); await _inspectionService.CompletedSign(singid, result); return result; } @@ -448,7 +442,7 @@ namespace IRaCIS.Core.API.Controllers public async Task CheckBack(DataInspectionDto opt) { var singid = await _inspectionService.RecordSing(opt.SignInfo); - var result = await _qCOperationService.CheckBack(opt.Data.Id); + var result = await _qCOperationService.CheckBack(opt.Data.Id); await _inspectionService.CompletedSign(singid, result); return result; } @@ -477,7 +471,7 @@ namespace IRaCIS.Core.API.Controllers [HttpPost, Route("Inspection/QCOperation/SetReuploadFinished")] [TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })] [UnitOfWork] - public async Task SetReuploadFinished(DataInspectionDto opt) + public async Task SetReuploadFinished(DataInspectionDto opt) { var singid = await _inspectionService.RecordSing(opt.SignInfo); var result = await _qCOperationService.SetReuploadFinished(opt.Data); @@ -528,13 +522,13 @@ namespace IRaCIS.Core.API.Controllers [TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })] [UnitOfWork] - public async Task ConfirmReReading(DataInspectionDto opt , [FromServices] IVisitTaskHelpeService _visitTaskCommonService,[FromServices] IVisitTaskService _visitTaskService) + public async Task ConfirmReReading(DataInspectionDto opt, [FromServices] IVisitTaskHelpeService _visitTaskCommonService, [FromServices] IVisitTaskService _visitTaskService) { var singId = await _inspectionService.RecordSing(opt.SignInfo); var result = await _visitTaskService.ConfirmReReading(opt.Data, _visitTaskCommonService); await _inspectionService.CompletedSign(singId, result); return result; } - + } } diff --git a/IRaCIS.Core.API/Controllers/UploadDownLoadController.cs b/IRaCIS.Core.API/Controllers/UploadDownLoadController.cs index 9e394116b..c5c59db31 100644 --- a/IRaCIS.Core.API/Controllers/UploadDownLoadController.cs +++ b/IRaCIS.Core.API/Controllers/UploadDownLoadController.cs @@ -1,9 +1,6 @@ using AutoMapper; -using DocumentFormat.OpenXml.Drawing; using ExcelDataReader; -using IRaCIS.Application.Contracts; using IRaCIS.Application.Interfaces; -using IRaCIS.Core.Application.Auth; using IRaCIS.Core.Application.Contracts; using IRaCIS.Core.Application.Contracts.Dicom; using IRaCIS.Core.Application.Contracts.Dicom.DTO; @@ -11,21 +8,16 @@ using IRaCIS.Core.Application.Filter; using IRaCIS.Core.Application.Helper; using IRaCIS.Core.Application.MassTransit.Command; using IRaCIS.Core.Application.Service; -using IRaCIS.Core.Application.Service.ImageAndDoc; -using IRaCIS.Core.Application.Service.Reading.Dto; using IRaCIS.Core.Domain.Models; using IRaCIS.Core.Domain.Share; using IRaCIS.Core.Infra.EFCore; using IRaCIS.Core.Infrastructure; using IRaCIS.Core.Infrastructure.Extention; -using MassTransit; using MassTransit.Mediator; using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Cors.Infrastructure; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.SignalR; using Microsoft.AspNetCore.StaticFiles; using Microsoft.AspNetCore.WebUtilities; @@ -40,12 +32,10 @@ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Data; -using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; -using ZiggyCreatures.Caching.Fusion; using Path = System.IO.Path; namespace IRaCIS.Core.API.Controllers @@ -451,7 +441,7 @@ namespace IRaCIS.Core.API.Controllers IsSuccess = false, UploadStartTime = DateTime.Now, - FileCount=preArchiveStudyCommand.FileCount, + FileCount = preArchiveStudyCommand.FileCount, IsDicom = preArchiveStudyCommand.IsDicom, IP = _userInfo.IP }; diff --git a/IRaCIS.Core.API/Progranm.cs b/IRaCIS.Core.API/Progranm.cs index fab8c9ecb..c4618643d 100644 --- a/IRaCIS.Core.API/Progranm.cs +++ b/IRaCIS.Core.API/Progranm.cs @@ -1,45 +1,27 @@ -using System; -using Autofac.Extensions.DependencyInjection; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Configuration; -using Serilog; -using System.Threading.Tasks; +using IRaCIS.Core.API; +using IRaCIS.Core.Application.BusinessFilter; +using IRaCIS.Core.Application.Filter; +using IRaCIS.Core.Application.Service.BackGroundJob; +using IRaCIS.Core.Infra.EFCore; +using IRaCIS.Core.Infrastructure.Extention; +using LogDashboard; using MassTransit; using MassTransit.NewIdProviders; -using System.IO; -using IRaCIS.Core.Domain.Share; -using IRaCIS.Core.Infra.EFCore; -using IRaCIS.Core.Application.Helper; -using System.Runtime.InteropServices; using Microsoft.AspNetCore.Builder; -using IRaCIS.Core.API; -using Autofac; -using Microsoft.AspNetCore.Http.Features; -using Microsoft.AspNetCore.SignalR; -using Microsoft.Extensions.DependencyInjection; -using IRaCIS.Core.Application.Filter; -using Microsoft.AspNetCore.HttpOverrides; -using IRaCIS.Core.Application.Service.BackGroundJob; -using LogDashboard; -using FellowOakDicom.Network; -using IRaCIS.Core.Application.Service.ImageAndDoc; -using IP2Region.Net.Abstractions; -using IP2Region.Net.XDB; -using IRaCIS.Core.Application.BusinessFilter; +using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; -using IRaCIS.Core.Infrastructure.Extention; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Newtonsoft.Json; -using Microsoft.AspNetCore.Diagnostics; -using IRaCIS.Core.Application.MassTransit.Command; -using IRaCIS.Core.Application.MassTransit.Consumer; -using DocumentFormat.OpenXml.InkML; -using IRaCIS.Core.Domain; -using MassTransit.Internals; -using IRaCIS.Core.Domain.BaseModel; +using Serilog; +using System; +using System.IO; +using System.Runtime.InteropServices; AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true); + #region 获取环境变量 //以配置文件为准,否则 从url中取环境值(服务以命令行传递参数启动,配置文件配置了就不需要传递环境参数) var config = new ConfigurationBuilder() @@ -89,19 +71,26 @@ NewId.SetProcessIdProvider(new CurrentProcessIdProvider()); builder.Configuration.AddJsonFile(ConfigMapFileProvider.FromRelativePath(""), "appsettings.json", false, true) .AddJsonFile(ConfigMapFileProvider.FromRelativePath(""), $"appsettings.{enviromentName}.json", false, true); -builder.Host - .UseServiceProviderFactory(new AutofacServiceProviderFactory()) - .ConfigureContainer(containerBuilder => - { - containerBuilder.RegisterModule(); - }) - .UseWindowsService().UseSerilog(); +builder.Host.UseSerilog(); + + +#region Autofac 废弃 +//builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()) +// .ConfigureContainer(containerBuilder => +// { +// containerBuilder.RegisterModule(); +// }).UseWindowsService(); +#endregion + #endregion #region 配置服务 var _configuration = builder.Configuration; +//手动注册服务 +builder.Services.ConfigureServices(_configuration); + //健康检查 builder.Services.AddHealthChecks(); //本地化 @@ -121,16 +110,6 @@ builder.Services.AddControllers(options => }) .AddNewtonsoftJsonSetup(builder.Services); // NewtonsoftJson 序列化 处理 -builder.Services.AddOptions().Configure(_configuration.GetSection("SystemEmailSendConfig")); -builder.Services.AddOptions().Configure(_configuration.GetSection("BasicSystemConfig")); -builder.Services.AddOptions().Configure(_configuration.GetSection("AliyunOSS")); -builder.Services.AddOptions().Configure(_configuration.GetSection("ObjectStoreService")); -builder.Services.AddOptions().Configure(_configuration.GetSection("EncrypteResponseConfig")); -builder.Services.AddOptions().Configure(_configuration.GetSection("SystemPacsConfig")); - -builder.Services.Configure(_configuration.GetSection("IRaCISBasicConfig")); - - //动态WebApi + UnifiedApiResultFilter 省掉控制器代码 builder.Services.AddDynamicWebApiSetup(); //AutoMapper @@ -144,116 +123,29 @@ builder.Services.AddSwaggerSetup(); //JWT Token 验证 builder.Services.AddJWTAuthSetup(_configuration); -// MediatR 进程内消息 事件解耦 从程序集中 注册命令和handler对应关系 -//builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblyContaining()); - -#region MassTransit -//masstransit组件 也支持MediatR 中介者模式,但是支持分布式,考虑后续,所以在次替代MediatR -//参考链接:https://masstransit.io/documentation/concepts/mediator#scoped-mediator -builder.Services.AddMediator(cfg => -{ - cfg.AddConsumers(typeof(UserSiteSurveySubmitedEventConsumer).Assembly); - - //cfg.AddConsumer(); - //cfg.AddConsumer(); - //cfg.AddConsumer(); - //cfg.ConfigureMediator((context, cfg) => cfg.UseHttpContextScopeFilter(context)); -}); - -//添加 MassTransit 和 InMemory 传输 -builder.Services.AddMassTransit(cfg => -{ - // 自动扫描程序集中的消费者并进行注册 - cfg.AddConsumers(typeof(UserSiteSurveySubmitedEventConsumer).Assembly); - - //// 注册消费者 - //cfg.AddConsumer(); // 替换为你的消费者类 - //cfg.AddConsumer(); - - cfg.AddPublishMessageScheduler(); - //cfg.AddHangfireConsumers(); - - - - // 使用 InMemory 作为消息传递机制 - cfg.UsingInMemory((context, cfg) => - { - //https://github.com/MassTransit/Sample-Hangfire/blob/master/src/Sample.Hangfire.Console/Program.cs - cfg.UsePublishMessageScheduler(); - - //使用 Hangfire 进行消息调度 - cfg.UseHangfireScheduler(); - - cfg.UseConsumeFilter(typeof(CultureInfoFilter<>), context, - x => x.Include(type => type.IsAssignableTo(typeof(DomainEvent)))); - - - // 这里可以进行额外的配置 - cfg.ConfigureEndpoints(context); // 自动配置所有消费者的端点 - - }); -}); - -//builder.Services.AddOptions().Configure(options => -//{ -// options.WaitUntilStarted = true; -//}); -#endregion - - -#region FusionCache +//MassTransit +builder.Services.AddMassTransitSetup(); +// FusionCache builder.Services.AddFusionCache(); -#endregion - -// EasyCaching 缓存 -//builder.Services.AddEasyCachingSetup(_configuration); - // hangfire 定时任务框架 有界面,更友好~ builder.Services.AddhangfireSetup(_configuration); - //Serilog 日志可视化 LogDashboard日志 builder.Services.AddLogDashboardSetup(); - -builder.Services.AddJsonConfigSetup(_configuration); -//转发头设置 获取真实IP -builder.Services.Configure(options => -{ - options.ForwardedHeaders = - ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; -}); //Dicom影像渲染图片 跨平台 builder.Services.AddDicomSetup(); // 实时应用 builder.Services.AddSignalR(); -builder.Services.AddSingleton(); - - -builder.Services.AddSingleton(new Searcher(CachePolicy.Content, Path.Combine(AppContext.BaseDirectory, StaticData.Folder.Resources, "ip2region.xdb"))); - +//异常处理 //builder.Services.AddExceptionHandler(); //builder.Services.AddProblemDetails(); -#region 历史废弃配置 -//builder.Services.AddMemoryCache(); -////上传限制 配置 -//builder.Services.Configure(options => -//{ -// options.MultipartBodyLengthLimit = int.MaxValue; -// options.ValueCountLimit = int.MaxValue; -// options.ValueLengthLimit = int.MaxValue; -//}); -//IP 限流 可设置白名单 或者黑名单 -//services.AddIpPolicyRateLimitSetup(_configuration); -// 用户类型 策略授权 -//services.AddAuthorizationPolicySetup(_configuration); -#endregion #endregion diff --git a/IRaCIS.Core.API/SignalRHub/UploadHub.cs b/IRaCIS.Core.API/SignalRHub/UploadHub.cs index 961a9227b..662c298d9 100644 --- a/IRaCIS.Core.API/SignalRHub/UploadHub.cs +++ b/IRaCIS.Core.API/SignalRHub/UploadHub.cs @@ -38,7 +38,7 @@ namespace IRaCIS.Core.API public override Task OnConnectedAsync() { //base.Context.User.id - + _logger.LogError("连接: " + Context.ConnectionId); diff --git a/IRaCIS.Core.API/Utility/FileHelpers.cs b/IRaCIS.Core.API/Utility/FileHelpers.cs index a77ac0473..8c2f467ad 100644 --- a/IRaCIS.Core.API/Utility/FileHelpers.cs +++ b/IRaCIS.Core.API/Utility/FileHelpers.cs @@ -1,3 +1,7 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.AspNetCore.WebUtilities; +using Microsoft.Net.Http.Headers; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; @@ -6,10 +10,6 @@ using System.Linq; using System.Net; using System.Reflection; using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc.ModelBinding; -using Microsoft.AspNetCore.WebUtilities; -using Microsoft.Net.Http.Headers; namespace IRaCIS.Core.API.Utility { @@ -36,9 +36,9 @@ namespace IRaCIS.Core.API.Utility new byte[] { 0xFF, 0xD8, 0xFF, 0xE8 }, } }, - { ".zip", new List + { ".zip", new List { - new byte[] { 0x50, 0x4B, 0x03, 0x04 }, + new byte[] { 0x50, 0x4B, 0x03, 0x04 }, new byte[] { 0x50, 0x4B, 0x4C, 0x49, 0x54, 0x45 }, new byte[] { 0x50, 0x4B, 0x53, 0x70, 0x58 }, new byte[] { 0x50, 0x4B, 0x05, 0x06 }, @@ -55,8 +55,8 @@ namespace IRaCIS.Core.API.Utility // systems. For more information, see the topic that accompanies this sample // app. - public static async Task ProcessFormFile(IFormFile formFile, - ModelStateDictionary modelState, string[] permittedExtensions, + public static async Task ProcessFormFile(IFormFile formFile, + ModelStateDictionary modelState, string[] permittedExtensions, long sizeLimit) { var fieldDisplayName = string.Empty; @@ -88,12 +88,12 @@ namespace IRaCIS.Core.API.Utility // a BOM as their content. if (formFile.Length == 0) { - modelState.AddModelError(formFile.Name, + modelState.AddModelError(formFile.Name, $"{fieldDisplayName}({trustedFileNameForDisplay}) is empty."); return new byte[0]; } - + if (formFile.Length > sizeLimit) { var megabyteSizeLimit = sizeLimit / 1048576; @@ -143,7 +143,7 @@ namespace IRaCIS.Core.API.Utility } public static async Task ProcessStreamedFile( - MultipartSection section, ContentDispositionHeaderValue contentDisposition, + MultipartSection section, ContentDispositionHeaderValue contentDisposition, ModelStateDictionary modelState, string[] permittedExtensions, long sizeLimit) { try @@ -164,7 +164,7 @@ namespace IRaCIS.Core.API.Utility $"The file exceeds {megabyteSizeLimit:N1} MB."); } else if (!IsValidFileExtensionAndSignature( - contentDisposition.FileName.Value, memoryStream, + contentDisposition.FileName.Value, memoryStream, permittedExtensions)) { modelState.AddModelError("File", diff --git a/IRaCIS.Core.API/Utility/Jwt/CustomHSJWTService.cs b/IRaCIS.Core.API/Utility/Jwt/CustomHSJWTService.cs index 26e61286f..acd86df3c 100644 --- a/IRaCIS.Core.API/Utility/Jwt/CustomHSJWTService.cs +++ b/IRaCIS.Core.API/Utility/Jwt/CustomHSJWTService.cs @@ -1,12 +1,9 @@ using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using System; -using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; -using System.Linq; using System.Security.Claims; using System.Text; -using System.Threading.Tasks; namespace ZhaoXi._001.NET5Demo.Practice.WebApi.Utility.Jwt { diff --git a/IRaCIS.Core.API/Utility/Jwt/CustomRSSJWTervice.cs b/IRaCIS.Core.API/Utility/Jwt/CustomRSSJWTervice.cs index b93b444d6..d48826af0 100644 --- a/IRaCIS.Core.API/Utility/Jwt/CustomRSSJWTervice.cs +++ b/IRaCIS.Core.API/Utility/Jwt/CustomRSSJWTervice.cs @@ -1,13 +1,10 @@ using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using System; -using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.IO; -using System.Linq; using System.Security.Claims; using System.Security.Cryptography; -using System.Threading.Tasks; namespace ZhaoXi._001.NET5Demo.Practice.WebApi.Utility.Jwt { diff --git a/IRaCIS.Core.API/Utility/Jwt/ICustomJWTService.cs b/IRaCIS.Core.API/Utility/Jwt/ICustomJWTService.cs index ac1af958f..b3854f420 100644 --- a/IRaCIS.Core.API/Utility/Jwt/ICustomJWTService.cs +++ b/IRaCIS.Core.API/Utility/Jwt/ICustomJWTService.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace ZhaoXi._001.NET5Demo.Practice.WebApi.Utility.Jwt +namespace ZhaoXi._001.NET5Demo.Practice.WebApi.Utility.Jwt { public interface ICustomJWTService { diff --git a/IRaCIS.Core.API/Utility/Jwt/JWTTokenOptions.cs b/IRaCIS.Core.API/Utility/Jwt/JWTTokenOptions.cs index e8a087681..0b8662d9b 100644 --- a/IRaCIS.Core.API/Utility/Jwt/JWTTokenOptions.cs +++ b/IRaCIS.Core.API/Utility/Jwt/JWTTokenOptions.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace ZhaoXi._001.NET5Demo.Practice.WebApi.Utility.Jwt +namespace ZhaoXi._001.NET5Demo.Practice.WebApi.Utility.Jwt { public class JWTTokenOptions { diff --git a/IRaCIS.Core.API/Utility/Jwt/RSAHelper.cs b/IRaCIS.Core.API/Utility/Jwt/RSAHelper.cs index 707ba4630..09b5e394a 100644 --- a/IRaCIS.Core.API/Utility/Jwt/RSAHelper.cs +++ b/IRaCIS.Core.API/Utility/Jwt/RSAHelper.cs @@ -1,10 +1,6 @@ using Newtonsoft.Json; -using System; -using System.Collections.Generic; using System.IO; -using System.Linq; using System.Security.Cryptography; -using System.Threading.Tasks; namespace ZhaoXi._001.NET5Demo.Practice.WebApi.Utility.Jwt { diff --git a/IRaCIS.Core.API/Utility/MultipartRequestHelper.cs b/IRaCIS.Core.API/Utility/MultipartRequestHelper.cs index 11aa8cd92..0e1e240cc 100644 --- a/IRaCIS.Core.API/Utility/MultipartRequestHelper.cs +++ b/IRaCIS.Core.API/Utility/MultipartRequestHelper.cs @@ -1,6 +1,6 @@ +using Microsoft.Net.Http.Headers; using System; using System.IO; -using Microsoft.Net.Http.Headers; namespace IRaCIS.Core.API.Utility { diff --git a/IRaCIS.Core.API/_PipelineExtensions/HangfireConfig.cs b/IRaCIS.Core.API/_PipelineExtensions/HangfireConfig.cs index 873aac78f..9d03d88f7 100644 --- a/IRaCIS.Core.API/_PipelineExtensions/HangfireConfig.cs +++ b/IRaCIS.Core.API/_PipelineExtensions/HangfireConfig.cs @@ -1,9 +1,6 @@ using Hangfire; using Hangfire.Dashboard; using Hangfire.Dashboard.BasicAuthorization; -using IRaCIS.Core.Application.Service.BackGroundJob; -using IRaCIS.Core.API.Filter; -using IRaCIS.Core.Application.Helper; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; @@ -39,7 +36,7 @@ namespace IRaCIS.Core.API }) }, - DashboardTitle ="后台任务管理", + DashboardTitle = "后台任务管理", //Authorization = new BasicAuthAuthorizationFilter[] { diff --git a/IRaCIS.Core.API/_PipelineExtensions/IRacisHostFile/MultiDiskStaticFilesMiddleware.cs b/IRaCIS.Core.API/_PipelineExtensions/IRacisHostFile/MultiDiskStaticFilesMiddleware.cs index 3ac9b2bd1..881ffa12b 100644 --- a/IRaCIS.Core.API/_PipelineExtensions/IRacisHostFile/MultiDiskStaticFilesMiddleware.cs +++ b/IRaCIS.Core.API/_PipelineExtensions/IRacisHostFile/MultiDiskStaticFilesMiddleware.cs @@ -1,21 +1,12 @@ -using Azure; -using IRaCIS.Core.Application.Helper; +using IRaCIS.Core.Application.Helper; using IRaCIS.Core.Domain.Share; using IRaCIS.Core.Infrastructure.Extention; -using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.StaticFiles; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.FileProviders.Physical; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Hosting.Internal; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using Microsoft.VisualBasic; using Newtonsoft.Json; -using SharpCompress.Common; using System.IO; using System.Linq; using System.Threading.Tasks; @@ -32,7 +23,7 @@ namespace IRaCIS.Core.API private string iRaCISDefaultDataFolder = string.Empty; - public MultiDiskStaticFilesMiddleware(RequestDelegate next, IWebHostEnvironment hostingEnv, ILoggerFactory loggerFactory) + public MultiDiskStaticFilesMiddleware(RequestDelegate next, IWebHostEnvironment hostingEnv, ILoggerFactory loggerFactory) { _next = next; _hostingEnv = hostingEnv; @@ -89,7 +80,7 @@ namespace IRaCIS.Core.API if (defaultFileProvider.GetFileInfo(path).Exists) { - var actrualPath = defaultFileProvider.GetFileInfo(path).PhysicalPath; + var actrualPath = defaultFileProvider.GetFileInfo(path).PhysicalPath; await context.Response.SendFileAsync(new PhysicalFileInfo(new FileInfo(actrualPath))); @@ -110,7 +101,7 @@ namespace IRaCIS.Core.API .Where(d => d.IsReady && d.DriveType == DriveType.Fixed)/*.Where(t => !t.Name.Contains("C") && !t.Name.Contains("c"))*/ .OrderBy(d => d.AvailableFreeSpace) .Select(d => d.RootDirectory.FullName) - .ToArray().Where(t=>!t.Contains(defaultRoot)); + .ToArray().Where(t => !t.Contains(defaultRoot)); foreach (var item in disks) @@ -121,10 +112,10 @@ namespace IRaCIS.Core.API { continue; } - - var otherFileProvider= new PhysicalFileProvider(otherFileStoreFolder); - + var otherFileProvider = new PhysicalFileProvider(otherFileStoreFolder); + + if (otherFileProvider.GetFileInfo(path).Exists) { @@ -132,7 +123,7 @@ namespace IRaCIS.Core.API var actrualPath = otherFileProvider.GetFileInfo(path).PhysicalPath; //方式一 - await context.Response.SendFileAsync( new PhysicalFileInfo(new FileInfo(actrualPath))); + await context.Response.SendFileAsync(new PhysicalFileInfo(new FileInfo(actrualPath))); #region 方式二 报错 otherFileProvider 应该还包含/{StaticData.Folder.IRaCISDataFolder} 这一层级 //var otherStaticFileOptions = new StaticFileOptions @@ -158,7 +149,7 @@ namespace IRaCIS.Core.API await context.Response.WriteAsync(JsonConvert.SerializeObject(ResponseOutput.NotOk("File not found"))); } - + // 如果所有磁盘都不存在所请求的文件,则将请求传递给下一个中间件组件。 await _next.Invoke(context); diff --git a/IRaCIS.Core.API/_PipelineExtensions/LocalizationConfig.cs b/IRaCIS.Core.API/_PipelineExtensions/LocalizationConfig.cs index d94b96b65..cad560c86 100644 --- a/IRaCIS.Core.API/_PipelineExtensions/LocalizationConfig.cs +++ b/IRaCIS.Core.API/_PipelineExtensions/LocalizationConfig.cs @@ -1,6 +1,5 @@ using IRaCIS.Core.Domain.Share; using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Localization; using System.Collections.Generic; using System.Globalization; @@ -13,7 +12,7 @@ namespace IRaCIS.Core.API { var supportedCultures = new List { - + new CultureInfo(StaticData.CultureInfo.en_US), new CultureInfo(StaticData.CultureInfo.zh_CN) }; diff --git a/IRaCIS.Core.API/_PipelineExtensions/LogDashboard/LogDashBoardAuthFilter.cs b/IRaCIS.Core.API/_PipelineExtensions/LogDashboard/LogDashBoardAuthFilter.cs index 2fd35eae6..b644df0e3 100644 --- a/IRaCIS.Core.API/_PipelineExtensions/LogDashboard/LogDashBoardAuthFilter.cs +++ b/IRaCIS.Core.API/_PipelineExtensions/LogDashboard/LogDashBoardAuthFilter.cs @@ -3,7 +3,7 @@ using LogDashboard.Authorization; namespace IRaCIS.Core.API.Filter { - + public class LogDashBoardAuthFilter : ILogDashboardAuthorizationFilter { //在此可以利用 本系统的UerTypeEnum 判断 diff --git a/IRaCIS.Core.API/_PipelineExtensions/Serilog/RequestResponseLoggingMiddleware.cs b/IRaCIS.Core.API/_PipelineExtensions/Serilog/RequestResponseLoggingMiddleware.cs index 112314b65..ee61eabbc 100644 --- a/IRaCIS.Core.API/_PipelineExtensions/Serilog/RequestResponseLoggingMiddleware.cs +++ b/IRaCIS.Core.API/_PipelineExtensions/Serilog/RequestResponseLoggingMiddleware.cs @@ -1,5 +1,4 @@ using Microsoft.AspNetCore.Http; -using Serilog; using Serilog.Context; using System; using System.IO; diff --git a/IRaCIS.Core.API/_PipelineExtensions/Serilog/SerilogConfig.cs b/IRaCIS.Core.API/_PipelineExtensions/Serilog/SerilogConfig.cs index cccd58245..e4f418057 100644 --- a/IRaCIS.Core.API/_PipelineExtensions/Serilog/SerilogConfig.cs +++ b/IRaCIS.Core.API/_PipelineExtensions/Serilog/SerilogConfig.cs @@ -1,13 +1,11 @@ -using Hangfire; -using Hangfire.Dashboard; -using IRaCIS.Core.API._PipelineExtensions.Serilog; +using IRaCIS.Core.API._PipelineExtensions.Serilog; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Serilog; namespace IRaCIS.Core.API { - + public static class SerilogConfig { diff --git a/IRaCIS.Core.API/_PipelineExtensions/Serilog/SerilogHelper.cs b/IRaCIS.Core.API/_PipelineExtensions/Serilog/SerilogHelper.cs index 3e4c2aa59..7df3c4267 100644 --- a/IRaCIS.Core.API/_PipelineExtensions/Serilog/SerilogHelper.cs +++ b/IRaCIS.Core.API/_PipelineExtensions/Serilog/SerilogHelper.cs @@ -1,11 +1,6 @@ using IRaCIS.Core.Domain.Share; -using IRaCIS.Core.Infrastructure.Extention; using Microsoft.AspNetCore.Http; using Serilog; -using System; -using System.IO; -using System.Text; -using System.Threading.Tasks; namespace IRaCIS.Core.API { @@ -13,7 +8,7 @@ namespace IRaCIS.Core.API { //public static string RequestPayload = ""; - public static void EnrichFromRequest(IDiagnosticContext diagnosticContext, HttpContext httpContext) + public static void EnrichFromRequest(IDiagnosticContext diagnosticContext, HttpContext httpContext) { var request = httpContext.Request; diff --git a/IRaCIS.Core.API/_ServiceExtensions/Authorization/ApiResponseHandler.cs b/IRaCIS.Core.API/_ServiceExtensions/Authorization/ApiResponseHandler.cs index b0dceccf9..cd8df1d79 100644 --- a/IRaCIS.Core.API/_ServiceExtensions/Authorization/ApiResponseHandler.cs +++ b/IRaCIS.Core.API/_ServiceExtensions/Authorization/ApiResponseHandler.cs @@ -14,13 +14,13 @@ namespace IRaCIS.Core.API public class ApiResponseHandler : AuthenticationHandler { public IStringLocalizer _localizer; - public ApiResponseHandler(IOptionsMonitor options, - IStringLocalizer localizer, - ILoggerFactory logger, UrlEncoder encoder) : base(options, logger, encoder) + public ApiResponseHandler(IOptionsMonitor options, + IStringLocalizer localizer, + ILoggerFactory logger, UrlEncoder encoder) : base(options, logger, encoder) { _localizer = localizer; - } + } protected override Task HandleAuthenticateAsync() { @@ -30,7 +30,7 @@ namespace IRaCIS.Core.API { Response.ContentType = "application/json"; Response.StatusCode = StatusCodes.Status401Unauthorized; - //---您无权访问该接口 + //---您无权访问该接口 await Response.WriteAsync(JsonConvert.SerializeObject(ResponseOutput.NotOk(_localizer["ApiResponse_NoAccess"], ApiResponseCodeEnum.NoToken))); } @@ -38,8 +38,8 @@ namespace IRaCIS.Core.API { Response.ContentType = "application/json"; Response.StatusCode = StatusCodes.Status403Forbidden; - //---您的权限不允许进行该操作 - await Response.WriteAsync(JsonConvert.SerializeObject(ResponseOutput.NotOk(_localizer["ApiResponse_Permission"],ApiResponseCodeEnum.HaveTokenNotAccess))); + //---您的权限不允许进行该操作 + await Response.WriteAsync(JsonConvert.SerializeObject(ResponseOutput.NotOk(_localizer["ApiResponse_Permission"], ApiResponseCodeEnum.HaveTokenNotAccess))); } } diff --git a/IRaCIS.Core.API/_ServiceExtensions/Authorization/AuthorizationPolicySetup.cs b/IRaCIS.Core.API/_ServiceExtensions/Authorization/AuthorizationPolicySetup.cs index a6ea6138d..cad9b7146 100644 --- a/IRaCIS.Core.API/_ServiceExtensions/Authorization/AuthorizationPolicySetup.cs +++ b/IRaCIS.Core.API/_ServiceExtensions/Authorization/AuthorizationPolicySetup.cs @@ -34,7 +34,7 @@ namespace IRaCIS.Core.API { policyBuilder.RequireClaim("userTypeEnumInt", ((int)UserTypeEnum.ProjectManager).ToString(), ((int)UserTypeEnum.IQC).ToString()); }); - + options.AddPolicy(IRaCISPolicy.PM, policyBuilder => { @@ -54,7 +54,7 @@ namespace IRaCIS.Core.API options.AddPolicy(IRaCISPolicy.PM_APM_CRC_QC, policyBuilder => { - policyBuilder.RequireClaim("userTypeEnumInt", ((int)UserTypeEnum.ProjectManager).ToString(),((int)UserTypeEnum.ClinicalResearchCoordinator).ToString(), ((int)UserTypeEnum.APM).ToString(), ((int)UserTypeEnum.IQC).ToString()); + policyBuilder.RequireClaim("userTypeEnumInt", ((int)UserTypeEnum.ProjectManager).ToString(), ((int)UserTypeEnum.ClinicalResearchCoordinator).ToString(), ((int)UserTypeEnum.APM).ToString(), ((int)UserTypeEnum.IQC).ToString()); }); options.AddPolicy(IRaCISPolicy.SPM_CPM, policyBuilder => @@ -64,23 +64,23 @@ namespace IRaCIS.Core.API options.AddPolicy(IRaCISPolicy.PM_APM_SPM_CPM, policyBuilder => { - policyBuilder.RequireClaim("userTypeEnumInt", ((int)UserTypeEnum.ProjectManager).ToString(), ((int)UserTypeEnum.APM).ToString(),((int)UserTypeEnum.SPM).ToString(), ((int)UserTypeEnum.CPM).ToString()); + policyBuilder.RequireClaim("userTypeEnumInt", ((int)UserTypeEnum.ProjectManager).ToString(), ((int)UserTypeEnum.APM).ToString(), ((int)UserTypeEnum.SPM).ToString(), ((int)UserTypeEnum.CPM).ToString()); }); options.AddPolicy(IRaCISPolicy.PM_APM_SPM_CPM_SMM_CMM, policyBuilder => { - policyBuilder.RequireClaim("userTypeEnumInt", ((int)UserTypeEnum.ProjectManager).ToString(), ((int)UserTypeEnum.APM).ToString(), ((int)UserTypeEnum.SPM).ToString(), + policyBuilder.RequireClaim("userTypeEnumInt", ((int)UserTypeEnum.ProjectManager).ToString(), ((int)UserTypeEnum.APM).ToString(), ((int)UserTypeEnum.SPM).ToString(), ((int)UserTypeEnum.CPM).ToString(), ((int)UserTypeEnum.SMM).ToString(), ((int)UserTypeEnum.CMM).ToString()); }); - + }); } - + } } diff --git a/IRaCIS.Core.API/_ServiceExtensions/Authorization/JWTAuthSetup.cs b/IRaCIS.Core.API/_ServiceExtensions/Authorization/JWTAuthSetup.cs index dbe605f99..b6e6c509b 100644 --- a/IRaCIS.Core.API/_ServiceExtensions/Authorization/JWTAuthSetup.cs +++ b/IRaCIS.Core.API/_ServiceExtensions/Authorization/JWTAuthSetup.cs @@ -45,7 +45,7 @@ namespace IRaCIS.Core.API { OnMessageReceived = (context) => { - + if (context.Request.Query.TryGetValue("access_token", out StringValues values)) { var queryToken = values.FirstOrDefault(); @@ -58,10 +58,10 @@ namespace IRaCIS.Core.API } } - + //仅仅是访问文件的时候才会去取token认证 前端对cookie设置了有效期 - if (context.Request.Path.ToString().Contains("IRaCISData") || context.Request.Path.ToString().Contains("SystemData") ) + if (context.Request.Path.ToString().Contains("IRaCISData") || context.Request.Path.ToString().Contains("SystemData")) { var cookieToken = context.Request.Cookies["access_token"]; diff --git a/IRaCIS.Core.API/_ServiceExtensions/AutofacModuleSetup.cs b/IRaCIS.Core.API/_ServiceExtensions/AutofacModuleSetup.cs deleted file mode 100644 index d87a1cbed..000000000 --- a/IRaCIS.Core.API/_ServiceExtensions/AutofacModuleSetup.cs +++ /dev/null @@ -1,68 +0,0 @@ -using Autofac; -using IRaCIS.Core.Application; -using IRaCIS.Core.Application.BackGroundJob; -using IRaCIS.Core.Infra.EFCore; -using Microsoft.AspNetCore.Http; -using Panda.DynamicWebApi; -using System; -using System.Linq; -using System.Reflection; -using IRaCIS.Core.Domain.Models; -using IRaCIS.Core.Domain.Share; -using IRaCIS.Core.Application.Service; -using IRaCIS.Application.Interfaces; -using AutoMapper; - -namespace IRaCIS.Core.API -{ - // ReSharper disable once IdentifierTypo - public class AutofacModuleSetup : Autofac.Module - { - protected override void Load(ContainerBuilder containerBuilder) - { - - #region byzhouhang 20210917 此处注册泛型仓储 可以减少Domain层 和Infra.EFcore 两层 空的仓储接口定义和 仓储文件定义 - - containerBuilder.RegisterGeneric(typeof(Repository<>)) - .As(typeof(IRepository<>)).InstancePerLifetimeScope();//注册泛型仓储 - - containerBuilder.RegisterType().As().InstancePerLifetimeScope(); - - - #endregion - - #region 指定控制器也由autofac 来进行实例获取 https://www.cnblogs.com/xwhqwer/p/15320838.html - - //获取所有控制器类型并使用属性注入 - containerBuilder.RegisterAssemblyTypes(typeof(BaseService).Assembly) - .Where(type => typeof(IDynamicWebApi).IsAssignableFrom(type)) - .PropertiesAutowired(); - - - - #endregion - - - - - - - Assembly application = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + "IRaCIS.Core.Application.dll"); - containerBuilder.RegisterAssemblyTypes(application).Where(t => t.FullName.Contains("Service")) - .PropertiesAutowired().AsImplementedInterfaces(); - - - - //containerBuilder.RegisterType().As().SingleInstance(); - //containerBuilder.RegisterType().As().InstancePerLifetimeScope(); - - - //注册hangfire任务 依赖注入 - containerBuilder.RegisterType().As().InstancePerDependency(); - - - - - } - } -} \ No newline at end of file diff --git a/IRaCIS.Core.API/_ServiceExtensions/DynamicWebApiSetup.cs b/IRaCIS.Core.API/_ServiceExtensions/DynamicWebApiSetup.cs index 787c3918b..71a6fcae7 100644 --- a/IRaCIS.Core.API/_ServiceExtensions/DynamicWebApiSetup.cs +++ b/IRaCIS.Core.API/_ServiceExtensions/DynamicWebApiSetup.cs @@ -3,7 +3,7 @@ using Panda.DynamicWebApi; namespace IRaCIS.Core.API { - public static class DynamicWebApiSetup + public static class DynamicWebApiSetup { //20210910 避免冗余的控制器层代码编写,仅仅包了一层前后台定义的格式 这里采用动态webAPi+IResultFilter 替代大部分情况 public static void AddDynamicWebApiSetup(this IServiceCollection services) diff --git a/IRaCIS.Core.API/_ServiceExtensions/EFSetup.cs b/IRaCIS.Core.API/_ServiceExtensions/EFSetup.cs index 051cce253..b5619fe1a 100644 --- a/IRaCIS.Core.API/_ServiceExtensions/EFSetup.cs +++ b/IRaCIS.Core.API/_ServiceExtensions/EFSetup.cs @@ -1,5 +1,4 @@ using EntityFramework.Exceptions.SqlServer; -using Hangfire.SqlServer; using IRaCIS.Core.Application.Triggers; using IRaCIS.Core.Domain.Share; using IRaCIS.Core.Infra.EFCore; @@ -12,14 +11,12 @@ using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using StackExchange.Redis; namespace IRaCIS.Core.API { public static class EFSetup { - public static void AddEFSetup( this IServiceCollection services, IConfiguration configuration,string envName) + public static void AddEFSetup(this IServiceCollection services, IConfiguration configuration, string envName) { services.AddHttpContextAccessor(); @@ -37,9 +34,9 @@ namespace IRaCIS.Core.API // 在控制台 //public static readonly ILoggerFactory MyLoggerFactory = LoggerFactory.Create(builder => { builder.AddConsole(); }); - var logFactory = LoggerFactory.Create(builder => { builder.AddDebug(); }); + var logFactory = LoggerFactory.Create(builder => { builder.AddDebug(); }); - var dbType = configuration.GetSection("ConnectionStrings:Db_Type").Value ; + var dbType = configuration.GetSection("ConnectionStrings:Db_Type").Value; if (!string.IsNullOrWhiteSpace(dbType) && dbType == "pgsql") { options.UseNpgsql(configuration.GetSection("ConnectionStrings:RemoteNew").Value, contextOptionsBuilder => contextOptionsBuilder.EnableRetryOnFailure()); @@ -76,7 +73,7 @@ namespace IRaCIS.Core.API options.UseTriggers(triggerOptions => { triggerOptions.AddTrigger(); - triggerOptions.AddTrigger(); + triggerOptions.AddTrigger(); triggerOptions.AddTrigger(); triggerOptions.AddTrigger(); triggerOptions.AddTrigger(); diff --git a/IRaCIS.Core.API/_ServiceExtensions/IpPolicyRateLimitSetup.cs b/IRaCIS.Core.API/_ServiceExtensions/IpPolicyRateLimitSetup.cs index 74ea2228b..a835a681e 100644 --- a/IRaCIS.Core.API/_ServiceExtensions/IpPolicyRateLimitSetup.cs +++ b/IRaCIS.Core.API/_ServiceExtensions/IpPolicyRateLimitSetup.cs @@ -1,8 +1,6 @@ using AspNetCoreRateLimit; -using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using System; namespace IRaCIS.Core.API { @@ -13,7 +11,7 @@ namespace IRaCIS.Core.API { public static void AddIpPolicyRateLimitSetup(this IServiceCollection services, IConfiguration Configuration) { - + // needed to store rate limit counters and ip rules services.AddMemoryCache(); diff --git a/IRaCIS.Core.API/_ServiceExtensions/JsonConfigSetup.cs b/IRaCIS.Core.API/_ServiceExtensions/JsonConfigSetup.cs deleted file mode 100644 index 3707ae1a0..000000000 --- a/IRaCIS.Core.API/_ServiceExtensions/JsonConfigSetup.cs +++ /dev/null @@ -1,17 +0,0 @@ -using IRaCIS.Core.Domain.Share; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace IRaCIS.Core.API -{ - public static class JsonConfigSetup - { - public static void AddJsonConfigSetup(this IServiceCollection services, IConfiguration configuration) - { - - services.Configure(configuration.GetSection("BasicSystemConfig")); - - - } - } -} diff --git a/IRaCIS.Core.API/_ServiceExtensions/LogDashboardSetup.cs b/IRaCIS.Core.API/_ServiceExtensions/LogDashboardSetup.cs index 4042dfefe..208d0672b 100644 --- a/IRaCIS.Core.API/_ServiceExtensions/LogDashboardSetup.cs +++ b/IRaCIS.Core.API/_ServiceExtensions/LogDashboardSetup.cs @@ -1,11 +1,10 @@  using LogDashboard; -using LogDashboard.Authorization.Filters; using Microsoft.Extensions.DependencyInjection; namespace IRaCIS.Core.API { - public static class LogDashboardSetup + public static class LogDashboardSetup { public static void AddLogDashboardSetup(this IServiceCollection services) { diff --git a/IRaCIS.Core.API/_ServiceExtensions/MassTransitSetup.cs b/IRaCIS.Core.API/_ServiceExtensions/MassTransitSetup.cs new file mode 100644 index 000000000..9fa85fb74 --- /dev/null +++ b/IRaCIS.Core.API/_ServiceExtensions/MassTransitSetup.cs @@ -0,0 +1,66 @@ +using IRaCIS.Core.Application.MassTransit.Consumer; +using IRaCIS.Core.Domain.BaseModel; +using MassTransit; +using Microsoft.Extensions.DependencyInjection; + +namespace IRaCIS.Core.API +{ + public static class MassTransitSetup + { + public static void AddMassTransitSetup(this IServiceCollection services) + { + + + #region MassTransit + //masstransit组件 也支持MediatR 中介者模式,但是支持分布式,考虑后续,所以在次替代MediatR + //参考链接:https://masstransit.io/documentation/concepts/mediator#scoped-mediator + services.AddMediator(cfg => + { + cfg.AddConsumers(typeof(UserSiteSurveySubmitedEventConsumer).Assembly); + + //cfg.AddConsumer(); + //cfg.AddConsumer(); + //cfg.AddConsumer(); + //cfg.ConfigureMediator((context, cfg) => cfg.UseHttpContextScopeFilter(context)); + }); + + //添加 MassTransit 和 InMemory 传输 + services.AddMassTransit(cfg => + { + // 自动扫描程序集中的消费者并进行注册 + cfg.AddConsumers(typeof(UserSiteSurveySubmitedEventConsumer).Assembly); + + //// 注册消费者 + //cfg.AddConsumer(); // 替换为你的消费者类 + //cfg.AddConsumer(); + + cfg.AddPublishMessageScheduler(); + //cfg.AddHangfireConsumers(); + + + + // 使用 InMemory 作为消息传递机制 + cfg.UsingInMemory((context, cfg) => + { + //https://github.com/MassTransit/Sample-Hangfire/blob/master/src/Sample.Hangfire.Console/Program.cs + cfg.UsePublishMessageScheduler(); + + //使用 Hangfire 进行消息调度 + cfg.UseHangfireScheduler(); + + cfg.UseConsumeFilter(typeof(CultureInfoFilter<>), context, + x => x.Include(type => type.IsAssignableTo(typeof(DomainEvent)))); + + + // 这里可以进行额外的配置 + cfg.ConfigureEndpoints(context); // 自动配置所有消费者的端点 + + }); + }); + + #endregion + + + } + } +} diff --git a/IRaCIS.Core.API/_ServiceExtensions/NewtonsoftJson/JSONTimeZoneConverter.cs b/IRaCIS.Core.API/_ServiceExtensions/NewtonsoftJson/JSONTimeZoneConverter.cs index 0fada0af4..8a5658788 100644 --- a/IRaCIS.Core.API/_ServiceExtensions/NewtonsoftJson/JSONTimeZoneConverter.cs +++ b/IRaCIS.Core.API/_ServiceExtensions/NewtonsoftJson/JSONTimeZoneConverter.cs @@ -2,7 +2,6 @@ using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using Newtonsoft.Json.Converters; -using StackExchange.Redis; using System; using System.Globalization; @@ -14,9 +13,9 @@ namespace IRaCIS.Core.API public class JSONTimeZoneConverter(IHttpContextAccessor _httpContextAccessor) : DateTimeConverterBase { - private TimeZoneInfo _clientTimeZone; + private TimeZoneInfo _clientTimeZone; - private string _dateFormat; + private string _dateFormat; @@ -59,7 +58,7 @@ namespace IRaCIS.Core.API // 仅支持 DateTime 类型的转换 - return objectType == typeof(DateTime)|| objectType == typeof(DateTime?); + return objectType == typeof(DateTime) || objectType == typeof(DateTime?); } @@ -93,20 +92,20 @@ namespace IRaCIS.Core.API return null; } } - - + + // 将客户端时间转换为服务器时区的时间 var serverZoneTime = TimeZoneInfo.ConvertTime(dateTime, _clientTimeZone, TimeZoneInfo.Local); return serverZoneTime; - - + + } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) - { + { DateTime? nullableDateTime = value as DateTime?; if (nullableDateTime != null && nullableDateTime.HasValue) @@ -121,7 +120,7 @@ namespace IRaCIS.Core.API else { writer.WriteNull(); - } + } } } diff --git a/IRaCIS.Core.API/_ServiceExtensions/NewtonsoftJson/MyDateTimeConverter.cs b/IRaCIS.Core.API/_ServiceExtensions/NewtonsoftJson/MyDateTimeConverter.cs index 1ac9c501c..9a37b144f 100644 --- a/IRaCIS.Core.API/_ServiceExtensions/NewtonsoftJson/MyDateTimeConverter.cs +++ b/IRaCIS.Core.API/_ServiceExtensions/NewtonsoftJson/MyDateTimeConverter.cs @@ -1,10 +1,7 @@ using IRaCIS.Core.Domain.Share; -using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; using System; using System.Globalization; -using System.Reflection; namespace IRaCIS.Core.API { diff --git a/IRaCIS.Core.API/_ServiceExtensions/NewtonsoftJson/NewtonsoftJsonSetup.cs b/IRaCIS.Core.API/_ServiceExtensions/NewtonsoftJson/NewtonsoftJsonSetup.cs index f093d3678..14eda2f4f 100644 --- a/IRaCIS.Core.API/_ServiceExtensions/NewtonsoftJson/NewtonsoftJsonSetup.cs +++ b/IRaCIS.Core.API/_ServiceExtensions/NewtonsoftJson/NewtonsoftJsonSetup.cs @@ -1,16 +1,9 @@  using IRaCIS.Core.API._ServiceExtensions.NewtonsoftJson; using IRaCIS.Core.Application.Helper; -using IRaCIS.Core.Domain.Share; -using Microsoft.AspNetCore.Mvc.Infrastructure; -using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; -using Newtonsoft.Json.Converters; using System; -using System.Globalization; -using System.Text.Json; -using Newtonsoft.Json.Serialization; namespace IRaCIS.Core.API { diff --git a/IRaCIS.Core.API/_ServiceExtensions/NewtonsoftJson/NullToEmptyStringResolver.cs b/IRaCIS.Core.API/_ServiceExtensions/NewtonsoftJson/NullToEmptyStringResolver.cs index 21ebc8056..57ddbe733 100644 --- a/IRaCIS.Core.API/_ServiceExtensions/NewtonsoftJson/NullToEmptyStringResolver.cs +++ b/IRaCIS.Core.API/_ServiceExtensions/NewtonsoftJson/NullToEmptyStringResolver.cs @@ -35,7 +35,7 @@ namespace IRaCIS.Core.API // 检查类是否有 LowerCamelCaseJsonAttribute 标记 有的话,属性名小写 if (type.GetCustomAttribute() != null) { - base.NamingStrategy= new LowerCamelCaseNamingStrategy(); + base.NamingStrategy = new LowerCamelCaseNamingStrategy(); } else { @@ -46,7 +46,7 @@ namespace IRaCIS.Core.API IList properties = base.CreateProperties(type, memberSerialization); - var list= type.GetProperties() + var list = type.GetProperties() .Select(p => { var jp = base.CreateProperty(p, memberSerialization); @@ -57,10 +57,10 @@ namespace IRaCIS.Core.API var uu = list.Select(t => t.PropertyName).ToList(); //获取复杂对象属性 - properties = properties.TakeWhile(t => !uu.Contains(t.PropertyName)).ToList(); + properties = properties.TakeWhile(t => !uu.Contains(t.PropertyName)).ToList(); - list.AddRange(properties); - return list; + list.AddRange(properties); + return list; } diff --git a/IRaCIS.Core.API/_ServiceExtensions/NewtonsoftJson/NullToEmptyStringValueProvider.cs b/IRaCIS.Core.API/_ServiceExtensions/NewtonsoftJson/NullToEmptyStringValueProvider.cs index eb4e47de5..111f7d093 100644 --- a/IRaCIS.Core.API/_ServiceExtensions/NewtonsoftJson/NullToEmptyStringValueProvider.cs +++ b/IRaCIS.Core.API/_ServiceExtensions/NewtonsoftJson/NullToEmptyStringValueProvider.cs @@ -1,6 +1,6 @@ -using System; +using Newtonsoft.Json.Serialization; +using System; using System.Reflection; -using Newtonsoft.Json.Serialization; namespace IRaCIS.Core.API { @@ -25,17 +25,17 @@ namespace IRaCIS.Core.API public void SetValue(object target, object value) { - if(_MemberInfo.PropertyType == typeof(string)) + if (_MemberInfo.PropertyType == typeof(string)) { //去掉前后空格 - _MemberInfo.SetValue(target, value==null?string.Empty: value.ToString()==string.Empty? value:value/*.ToString().Trim()*/); - + _MemberInfo.SetValue(target, value == null ? string.Empty : value.ToString() == string.Empty ? value : value/*.ToString().Trim()*/); + } else { _MemberInfo.SetValue(target, value); } - + } } diff --git a/IRaCIS.Core.API/_ServiceExtensions/NewtonsoftJson/ObjectStorePathConvert.cs b/IRaCIS.Core.API/_ServiceExtensions/NewtonsoftJson/ObjectStorePathConvert.cs index e7d4aad48..1583fe0e6 100644 --- a/IRaCIS.Core.API/_ServiceExtensions/NewtonsoftJson/ObjectStorePathConvert.cs +++ b/IRaCIS.Core.API/_ServiceExtensions/NewtonsoftJson/ObjectStorePathConvert.cs @@ -1,8 +1,5 @@ using IRaCIS.Core.Application.Helper; -using Microsoft.AspNetCore.Http; using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Serialization; using System; using System.Linq; using System.Text.RegularExpressions; @@ -14,7 +11,7 @@ namespace IRaCIS.Core.API._ServiceExtensions.NewtonsoftJson private readonly IOSSService _oSSService; // 构造函数 - public ObjectStorePathConvert( IOSSService oSSService) + public ObjectStorePathConvert(IOSSService oSSService) { _oSSService = oSSService; } @@ -41,9 +38,9 @@ namespace IRaCIS.Core.API._ServiceExtensions.NewtonsoftJson Regex guidRegex = new Regex(@"[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}"); - if (propertyName.IndexOf("Path") > -1 && value.IndexOf('.')>-1 && guidRegex.IsMatch(value)) + if (propertyName.IndexOf("Path") > -1 && value.IndexOf('.') > -1 && guidRegex.IsMatch(value)) { - var tt= _oSSService.GetSignedUrl(value); + var tt = _oSSService.GetSignedUrl(value); writer.WriteValue(tt); } else @@ -51,13 +48,13 @@ namespace IRaCIS.Core.API._ServiceExtensions.NewtonsoftJson // 将处理后的字符串写入到 JsonWriter 中 writer.WriteValue(value); } - + } else { writer.WriteNull(); } } - + } } diff --git a/IRaCIS.Core.API/_ServiceExtensions/Serilog/HttpContextEnricher.cs b/IRaCIS.Core.API/_ServiceExtensions/Serilog/HttpContextEnricher.cs index afbbf681d..2f67772d4 100644 --- a/IRaCIS.Core.API/_ServiceExtensions/Serilog/HttpContextEnricher.cs +++ b/IRaCIS.Core.API/_ServiceExtensions/Serilog/HttpContextEnricher.cs @@ -1,14 +1,11 @@ -using IRaCIS.Core.Infrastructure; -using IRaCIS.Core.Infrastructure.Extention; +using IRaCIS.Core.Domain.Share; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Serilog.Core; using Serilog.Events; using System; using System.IO; -using System.Text; using System.Threading.Tasks; -using IRaCIS.Core.Domain.Share; namespace IRaCIS.Core.API { @@ -25,7 +22,7 @@ namespace IRaCIS.Core.API _serviceProvider = serviceProvider; if (enrichAction == null) { - _enrichAction = (logEvent, propertyFactory, httpContext) => + _enrichAction = (logEvent, propertyFactory, httpContext) => { logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("RequestIP", httpContext.Connection.RemoteIpAddress.ToString())); @@ -73,7 +70,7 @@ namespace IRaCIS.Core.API // Reset the request's body stream position for next middleware in the pipeline. request.Body.Position = 0; - return requestBody==null?String.Empty: requestBody.Trim(); + return requestBody == null ? String.Empty : requestBody.Trim(); } private async Task ReadResponseBody(HttpResponse response) diff --git a/IRaCIS.Core.API/_ServiceExtensions/Serilog/SerilogSetup.cs b/IRaCIS.Core.API/_ServiceExtensions/Serilog/SerilogSetup.cs index a010e8595..b7576f849 100644 --- a/IRaCIS.Core.API/_ServiceExtensions/Serilog/SerilogSetup.cs +++ b/IRaCIS.Core.API/_ServiceExtensions/Serilog/SerilogSetup.cs @@ -1,9 +1,7 @@ -using Microsoft.AspNetCore.Builder; -using Serilog; +using Serilog; using Serilog.Events; //using Serilog.Sinks.Email; using System; -using System.Net; namespace IRaCIS.Core.API { @@ -16,13 +14,13 @@ namespace IRaCIS.Core.API var config = new LoggerConfiguration() .MinimumLevel.Information() .MinimumLevel.Override("Microsoft", LogEventLevel.Information) - // Filter out ASP.NET Core infrastructre logs that are Information and below 日志太多了 一个请求 记录好几条 + // Filter out ASP.NET Core infrastructre logs that are Information and below 日志太多了 一个请求 记录好几条 .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning) .MinimumLevel.Override("Hangfire", LogEventLevel.Warning) - .MinimumLevel.Override("System.Net.Http.HttpClient.HttpReports", LogEventLevel.Warning) + .MinimumLevel.Override("System.Net.Http.HttpClient.HttpReports", LogEventLevel.Warning) .Enrich.WithClientIp() .Enrich.FromLogContext() - .Filter.ByExcluding(logEvent =>logEvent.Properties.ContainsKey("RequestPath") && logEvent.Properties["RequestPath"].ToString().Contains("/health")) + .Filter.ByExcluding(logEvent => logEvent.Properties.ContainsKey("RequestPath") && logEvent.Properties["RequestPath"].ToString().Contains("/health")) //控制台 方便调试 问题 我们显示记录日志 时 获取上下文的ip 和用户名 用户类型 .WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Warning, diff --git a/IRaCIS.Core.API/_ServiceExtensions/ServiceCollectionSetup.cs b/IRaCIS.Core.API/_ServiceExtensions/ServiceCollectionSetup.cs new file mode 100644 index 000000000..0593a0e31 --- /dev/null +++ b/IRaCIS.Core.API/_ServiceExtensions/ServiceCollectionSetup.cs @@ -0,0 +1,139 @@ +using Autofac; +using IP2Region.Net.Abstractions; +using IP2Region.Net.XDB; +using IRaCIS.Core.Application.BackGroundJob; +using IRaCIS.Core.Application.Helper; +using IRaCIS.Core.Application.Service; +using IRaCIS.Core.Application.Service.BackGroundJob; +using IRaCIS.Core.Domain.Share; +using IRaCIS.Core.Infra.EFCore; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.HttpOverrides; +using Microsoft.AspNetCore.SignalR; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Panda.DynamicWebApi; +using System; +using System.IO; +using System.Linq; +using System.Reflection; + +namespace IRaCIS.Core.API; + + +public static class ServiceCollectionSetup +{ + public static void ConfigureServices(this IServiceCollection services, IConfiguration _configuration) + { + services.AddOptions().Configure(_configuration.GetSection("SystemEmailSendConfig")); + services.AddOptions().Configure(_configuration.GetSection("BasicSystemConfig")); + services.AddOptions().Configure(_configuration.GetSection("AliyunOSS")); + services.AddOptions().Configure(_configuration.GetSection("ObjectStoreService")); + services.AddOptions().Configure(_configuration.GetSection("EncrypteResponseConfig")); + services.AddOptions().Configure(_configuration.GetSection("SystemPacsConfig")); + services.Configure(_configuration.GetSection("IRaCISBasicConfig")); + + services.Configure(_configuration.GetSection("BasicSystemConfig")); + + //תͷ ȡʵIP + services.Configure(options => + { + options.ForwardedHeaders = + ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; + }); + + services.AddSingleton(); + services.AddSingleton(new Searcher(CachePolicy.Content, Path.Combine(AppContext.BaseDirectory, StaticData.Folder.Resources, "ip2region.xdb"))); + + + + + services.AddScoped(typeof(IRepository<>), typeof(Repository<>)); + services.AddScoped(); + + services.AddScoped(); + services.AddScoped(); + + // עService βķ + services.Scan(scan => scan + .FromAssemblies(typeof(BaseService).Assembly) + .AddClasses(classes => classes.Where(t => t.Name.Contains("Service"))) + .AsImplementedInterfaces() + .WithScopedLifetime()); + + #region Register Controllers + + // Register all controllers in the assembly that implement IDynamicWebApi + services.Scan(scan => scan + .FromAssemblies(typeof(BaseService).Assembly) + .AddClasses(classes => classes.AssignableTo()) + .AsSelf() + .WithScopedLifetime()); + + #endregion + + + // MediatR Ϣ ¼ ӳ עhandlerӦϵ + //builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblyContaining()); + + + + #region ʷ + //builder.Services.AddMemoryCache(); + ////ϴ + //builder.Services.Configure(options => + //{ + // options.MultipartBodyLengthLimit = int.MaxValue; + // options.ValueCountLimit = int.MaxValue; + // options.ValueLengthLimit = int.MaxValue; + //}); + //IP ð ߺ + //services.AddIpPolicyRateLimitSetup(_configuration); + // û Ȩ + //services.AddAuthorizationPolicySetup(_configuration); + #endregion + } + + +} + +#region Autofac +public class AutofacModuleSetup : Autofac.Module +{ + protected override void Load(ContainerBuilder containerBuilder) + { + + #region byzhouhang 20210917 ˴ע᷺Ͳִ ԼDomain Infra.EFcore յIJִӿڶ ִļ + + containerBuilder.RegisterGeneric(typeof(Repository<>)) + .As(typeof(IRepository<>)).InstancePerLifetimeScope();//ע᷺Ͳִ + + containerBuilder.RegisterType().As().InstancePerLifetimeScope(); + + + #endregion + + #region ָҲautofac ʵȡ https://www.cnblogs.com/xwhqwer/p/15320838.html + + //ȡпͲʹע + containerBuilder.RegisterAssemblyTypes(typeof(BaseService).Assembly) + .Where(type => typeof(IDynamicWebApi).IsAssignableFrom(type)) + .PropertiesAutowired(); + + #endregion + + + Assembly application = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + "IRaCIS.Core.Application.dll"); + containerBuilder.RegisterAssemblyTypes(application).Where(t => t.FullName.Contains("Service")) + .PropertiesAutowired().AsImplementedInterfaces(); + + //containerBuilder.RegisterType().As().SingleInstance(); + //containerBuilder.RegisterType().As().InstancePerLifetimeScope(); + + + //עhangfire ע + containerBuilder.RegisterType().As().InstancePerDependency(); + + } +} +#endregion diff --git a/IRaCIS.Core.API/_ServiceExtensions/StaticFileAuthorizationSetup.cs b/IRaCIS.Core.API/_ServiceExtensions/StaticFileAuthorizationSetup.cs index 0ec0aa44b..8692cdd6a 100644 --- a/IRaCIS.Core.API/_ServiceExtensions/StaticFileAuthorizationSetup.cs +++ b/IRaCIS.Core.API/_ServiceExtensions/StaticFileAuthorizationSetup.cs @@ -3,7 +3,7 @@ using Microsoft.Extensions.DependencyInjection; namespace IRaCIS.Core.API { - public static class StaticFileAuthorizationSetup + public static class StaticFileAuthorizationSetup { public static void AddStaticFileAuthorizationSetup(this IServiceCollection services) { diff --git a/IRaCIS.Core.API/_ServiceExtensions/Swagger/SwaggerSetup.cs b/IRaCIS.Core.API/_ServiceExtensions/Swagger/SwaggerSetup.cs index a5c53cd7f..4104c3ce1 100644 --- a/IRaCIS.Core.API/_ServiceExtensions/Swagger/SwaggerSetup.cs +++ b/IRaCIS.Core.API/_ServiceExtensions/Swagger/SwaggerSetup.cs @@ -1,5 +1,4 @@ -using IRaCIS.Core.Application.Contracts; -using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; @@ -14,7 +13,7 @@ using System.Reflection; namespace IRaCIS.Core.API { - public static class SwaggerSetup + public static class SwaggerSetup { public static void AddSwaggerSetup(this IServiceCollection services) { @@ -23,20 +22,20 @@ namespace IRaCIS.Core.API { //此处的Name 是控制器上分组的名称 Title是界面的大标题 //分组 - - options.SwaggerDoc("Reviewer", new OpenApiInfo {Title = "医生模块",Version = "Reviewer", }); + + options.SwaggerDoc("Reviewer", new OpenApiInfo { Title = "医生模块", Version = "Reviewer", }); options.SwaggerDoc("Trial", new OpenApiInfo { Title = "项目模块", Version = "Trial" }); options.SwaggerDoc("Enroll", new OpenApiInfo { Title = "入组模块", Version = "Enroll" }); options.SwaggerDoc("Workload", new OpenApiInfo { Title = "工作量模块", Version = "Workload" }); options.SwaggerDoc("Common", new OpenApiInfo { Title = "通用信息获取", Version = "Common" }); options.SwaggerDoc("Institution", new OpenApiInfo { Title = "机构信息模块", Version = "Institution" }); options.SwaggerDoc("Dashboard&Statistics", new OpenApiInfo { Title = "统计模块", Version = "Dashboard&Statistics" }); - + options.SwaggerDoc("Financial", new OpenApiInfo { Title = "财务模块", Version = "Financial" }); options.SwaggerDoc("Management", new OpenApiInfo { Title = "管理模块", Version = "Management" }); options.SwaggerDoc("Image", new OpenApiInfo { Title = "影像模块", Version = "Image" }); options.SwaggerDoc("Reading", new OpenApiInfo { Title = "读片模块", Version = "Reading" }); - + // 接口排序 options.OrderActionsBy(o => o.GroupName); @@ -100,13 +99,13 @@ namespace IRaCIS.Core.API options.SwaggerEndpoint($"swagger/Workload/swagger.json", "工作量模块"); options.SwaggerEndpoint($"swagger/Dashboard&Statistics/swagger.json", "统计模块"); options.SwaggerEndpoint($"swagger/Common/swagger.json", "通用模块"); - + options.SwaggerEndpoint($"swagger/Financial/swagger.json", "财务模块"); options.SwaggerEndpoint($"swagger/Institution/swagger.json", "机构信息模块"); options.SwaggerEndpoint($"swagger/Management/swagger.json", "管理模块"); options.SwaggerEndpoint($"swagger/Image/swagger.json", "影像模块"); options.SwaggerEndpoint($"swagger/Reading/swagger.json", "读片模块"); - + //路径配置,设置为空,表示直接在根域名(localhost:8001)访问该文件, //注意localhost:8001/swagger是访问不到的,去launchSettings.json把launchUrl去掉,如果你想换一个路径,直接写名字即可,比如直接写c.Route = "doc"; @@ -128,7 +127,7 @@ namespace IRaCIS.Core.API // 清除静态文件缓存 // options.IndexStream = () => null; - + }); diff --git a/IRaCIS.Core.API/_ServiceExtensions/hangfireSetup.cs b/IRaCIS.Core.API/_ServiceExtensions/hangfireSetup.cs index 9dba5da6e..1e2eff9eb 100644 --- a/IRaCIS.Core.API/_ServiceExtensions/hangfireSetup.cs +++ b/IRaCIS.Core.API/_ServiceExtensions/hangfireSetup.cs @@ -26,10 +26,10 @@ namespace IRaCIS.Core.API //指定存储介质 hangFireConfig.UseSqlServerStorage(hangFireConnStr, new SqlServerStorageOptions() { - SchemaName = "dbo", + SchemaName = "dbo", }).UseRecommendedSerializerSettings().UseSimpleAssemblyNameTypeSerializer(); } - + //hangFireConfig.UseTagsWithSql(); //nuget引入Hangfire.Tags.SqlServer //.UseHangfireHttpJob();