AFR对接

master
zhangxiaofeng 11 months ago
parent 53adb7ffde
commit 9e1408d689

@ -129,6 +129,10 @@ namespace Common.DJYModel
[JsonProperty] [JsonProperty]
public DateTime? SENDTIME { get; set; } public DateTime? SENDTIME { get; set; }
/// <summary>
/// 0新增发送或原始重发 1修改发送 5删除发送
/// </summary>
[JsonProperty] [JsonProperty]
public int? SENDTYPE { get; set; } public int? SENDTYPE { get; set; }
/// <summary> /// <summary>

@ -6,28 +6,10 @@ namespace Common.Helpers
{ {
public class LogLock public class LogLock
{ {
//private static readonly ILog log = LogManager.GetLogger(typeof(LogLock));
private static ReaderWriterLockSlim LogWriteLock = new(); private static ReaderWriterLockSlim LogWriteLock = new();
//private static int WritedCount = 0;
//private static int FailedCount = 0;
private static string _contentRoot = string.Empty;
public LogLock(string contentPath)
{
_contentRoot = contentPath;
}
public static void LogRecordAccess(string[] dataParas, bool IsHeader = true, bool isWrt = false)
{
OutSql2LogToFile("RecordAccessLog", dataParas, IsHeader, isWrt);
}
public static void LogInfo(string[] dataParas, bool IsHeader = true, bool isWrt = false)
{
OutSql2LogToFile("InfoLog", dataParas, IsHeader, isWrt);
}
public static void LogSql(string[] dataParas, bool IsHeader = true, bool isWrt = false) public static void LogSql(string[] dataParas, bool IsHeader = true, bool isWrt = false)
{ {
OutSql2LogToFile("SqlLog", dataParas, IsHeader, isWrt); OutSql2LogToFile("sqlLog", dataParas, IsHeader, isWrt);
} }
public static void OutSql2LogToFile(string prefix, string[] dataParas, bool IsHeader = true, bool isWrt = false) public static void OutSql2LogToFile(string prefix, string[] dataParas, bool IsHeader = true, bool isWrt = false)
@ -39,15 +21,13 @@ namespace Common.Helpers
// 从性能方面考虑,请求进入写入模式应该紧跟文件操作之前,在此处进入写入模式仅是为了降低代码复杂度 // 从性能方面考虑,请求进入写入模式应该紧跟文件操作之前,在此处进入写入模式仅是为了降低代码复杂度
// 因进入与退出写入模式应在同一个try finally语句块内所以在请求进入写入模式之前不能触发异常否则释放次数大于请求次数将会触发异常 // 因进入与退出写入模式应在同一个try finally语句块内所以在请求进入写入模式之前不能触发异常否则释放次数大于请求次数将会触发异常
LogWriteLock.EnterWriteLock(); LogWriteLock.EnterWriteLock();
string folderPath = Path.Combine(_contentRoot, "Log", prefix); string folderPath = Path.Combine(AppContext.BaseDirectory, "Logs", DateTime.Now.ToString("yyyy-MM-dd"));
if (!Directory.Exists(folderPath)) if (!Directory.Exists(folderPath))
{ {
Directory.CreateDirectory(folderPath); Directory.CreateDirectory(folderPath);
} }
//string logFilePath = Path.Combine(path, $@"{filename}.log"); string logFilePath = Path.Combine(folderPath, $@"{prefix}.txt");
//string logFilePath = FileHelper.GetAvailableFileWithPrefixOrderSize(folderPath, prefix, 3145728);
string logFilePath = Path.Combine(folderPath, $@"{prefix}_{DateTime.Now.ToString("yyyy-MM-dd")}.log");
DateTime now = DateTime.Now; DateTime now = DateTime.Now;
string logContent; string logContent;
@ -87,37 +67,5 @@ namespace Common.Helpers
LogWriteLock.ExitWriteLock(); LogWriteLock.ExitWriteLock();
} }
} }
//public static void OutSql2LogToDB(string prefix, string[] dataParas, bool IsHeader = true)
//{
// string logContent = String.Join("", dataParas);
// if (IsHeader)
// {
// logContent = (String.Join("", dataParas));
// }
// switch (prefix)
// {
// case "AOPLog":
// log.Info(logContent);
// break;
// case "AOPLogEx":
// log.Error(logContent);
// break;
// case "RequestIpInfoLog":
// log.Debug(logContent);
// break;
// case "RecordAccessLogs":
// log.Debug(logContent);
// break;
// case "SqlLog":
// log.Info(logContent);
// break;
// case "RequestResponseLog":
// log.Debug(logContent);
// break;
// default:
// break;
// }
//}
} }
} }

@ -151,5 +151,24 @@ namespace Common.Tools
return Json.JsonToObject<T>(val); return Json.JsonToObject<T>(val);
} }
} }
/// <summary>
/// 读取redis中的对象数据 不存在返回null
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="Key"></param>
/// <returns></returns>
public static string RedisGetString(string Key)
{
var val = DbRedis.Get(Key);
if (val.IsNull())
{
return default;
}
else
{
return val;
}
}
} }
} }

@ -20,7 +20,8 @@ namespace djy.IService.Afr
#endregion #endregion
Task<PageModel<AFRMaster>> Load(AFRMasterInputDto input); Task<PageModel<AFRMaster>> Load(AFRMasterInputDto input);
Task SaveInfo(AFRMasterDto input); Task<AFRMaster> Get(string gid);
Task SaveInfo(AFRMaster input);
Task Delete(string ids); Task Delete(string ids);
Task Send(string ids, string msgType); Task Send(string ids, string msgType);
Task SaveReceipt(AFRReceiptDto input); Task SaveReceipt(AFRReceiptDto input);

@ -11,30 +11,6 @@ namespace djy.Model.AFR
[Column(IsPrimary = true)] [Column(IsPrimary = true)]
public string GID { get; set; } public string GID { get; set; }
/// <summary>
/// 用户ID
/// </summary>
public string UserID { get; set; }
/// <summary>
/// 用户名称
/// </summary>
public string UserName { get; set; }
/// <summary>
/// 公司ID
/// </summary>
public string CompID { get; set; }
/// <summary>
/// 公司名称
/// </summary>
public string CompName { get; set; }
/// <summary>
/// 是否删除
/// </summary>
public bool? IsDel { get; set; }
/// <summary> /// <summary>
/// 最后修改时间 /// 最后修改时间
/// </summary> /// </summary>
@ -44,7 +20,7 @@ namespace djy.Model.AFR
/// <summary> /// <summary>
/// 创建时间 /// 创建时间
/// </summary> /// </summary>
[Column(CanUpdate =false)] [Column(CanUpdate = false)]
public DateTime? CreateTime { get; set; } public DateTime? CreateTime { get; set; }
} }
} }

@ -11,6 +11,10 @@ namespace djy.Model.Afr
[Table(Name = "AFR_Cntrno", DisableSyncStructure = true)] [Table(Name = "AFR_Cntrno", DisableSyncStructure = true)]
public partial class AFRCntrno: AFRBaseModel public partial class AFRCntrno: AFRBaseModel
{ {
/// <summary>
/// 分单记录主键
/// </summary>
public string PID { get; set; }
/// <summary> /// <summary>
/// 货代提单号唯一编号 同货代提单号,原始修改删除重发报文,该值要一致 /// 货代提单号唯一编号 同货代提单号,原始修改删除重发报文,该值要一致
@ -97,10 +101,6 @@ namespace djy.Model.Afr
/// </summary> /// </summary>
public string PackingCode { get; set; } public string PackingCode { get; set; }
/// <summary>
///
/// </summary>
public string PID { get; set; }
/// <summary> /// <summary>
/// 封号 /// 封号

@ -2,6 +2,7 @@
using FreeSql.DataAnnotations; using FreeSql.DataAnnotations;
using NetTopologySuite.Geometries.Prepared; using NetTopologySuite.Geometries.Prepared;
using System; using System;
using System.Collections.Generic;
namespace djy.Model.Afr namespace djy.Model.Afr
{ {
@ -10,23 +11,38 @@ namespace djy.Model.Afr
/// ///
/// </summary> /// </summary>
[Table(Name = "AFR_House", DisableSyncStructure = true)] [Table(Name = "AFR_House", DisableSyncStructure = true)]
public partial class AFRHouse: AFRBaseModel public partial class AFRHouse : AFRBaseModel
{ {
/// <summary>
/// 主单主键
/// </summary>
public string PID { get; set; } public string PID { get; set; }
/// <summary>
/// 是否删除
/// </summary>
public bool IsDel { get; set; }
/// <summary> /// <summary>
/// 货代提单号唯一编号 同货代提单号,原始修改删除重发报文,该值要一致 /// 货代提单号唯一编号 同货代提单号,原始修改删除重发报文,该值要一致
/// </summary> /// </summary>
public string BusinessId { get; set; } public string BusinessId { get; set; }
/// <summary> /// <summary>
/// 货代提单号 修改报文,该值不可以变更 /// 货代提单号 修改报文,该值不可以变更
/// </summary> /// </summary>
public string HouseBillNo { get; set; } public string HouseBillNo { get; set; }
/// <summary>
/// 状态:海关接收
/// </summary>
public byte? StateIsAccept { get; set; }
/// <summary>
/// 状态:已匹配
/// </summary>
public byte? StateIsMatched { get; set; }
/// <summary> /// <summary>
/// 通知人地址 /// 通知人地址
@ -137,6 +153,14 @@ namespace djy.Model.Afr
/// 货代单运编号(选填) /// 货代单运编号(选填)
/// </summary> /// </summary>
public string ShippingNo { get; set; } public string ShippingNo { get; set; }
#region 导航属性
/// <summary>
/// 箱子列表
/// </summary>
[Navigate(nameof(AFRCntrno.PID))]
public List<AFRCntrno> CntrList { get; set; } = new List<AFRCntrno>();
#endregion
} }
} }

@ -12,6 +12,30 @@ namespace djy.Model.Afr
[Table(Name = "AFR_Master", DisableSyncStructure = true)] [Table(Name = "AFR_Master", DisableSyncStructure = true)]
public partial class AFRMaster : AFRBaseModel public partial class AFRMaster : AFRBaseModel
{ {
/// <summary>
/// 用户ID
/// </summary>
public string UserID { get; set; }
/// <summary>
/// 用户名称
/// </summary>
public string UserName { get; set; }
/// <summary>
/// 公司ID
/// </summary>
public string CompID { get; set; }
/// <summary>
/// 公司名称
/// </summary>
public string CompName { get; set; }
/// <summary>
/// 是否删除
/// </summary>
public bool IsDel { get; set; }
/// <summary> /// <summary>
/// 运输条款代码 /// 运输条款代码
/// </summary> /// </summary>
@ -76,7 +100,7 @@ namespace djy.Model.Afr
public string MBLNO { get; set; } public string MBLNO { get; set; }
/// <summary> /// <summary>
/// /// 船公司
/// </summary> /// </summary>
public string ShipCompany { get; set; } public string ShipCompany { get; set; }
@ -100,8 +124,14 @@ namespace djy.Model.Afr
/// <summary> /// <summary>
/// 分单列表 /// 分单列表
/// </summary> /// </summary>
[Navigate(nameof(AMS_Master.GID))] [Navigate(nameof(AFRHouse.PID))]
public List<AMS_House> Houses { get; set; } public List<AFRHouse> HouseList { get; set; } = new List<AFRHouse>();
/// <summary>
/// 操作历史
/// </summary>
[Navigate(nameof(AFRMasterHistory.PID))]
public AFRMasterHistory History { get; set; }
#endregion #endregion
} }

@ -3,14 +3,12 @@ using System;
namespace djy.Model.Afr namespace djy.Model.Afr
{ {
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
[Table(Name = "AFR_MasterHistory", DisableSyncStructure = true)] [Table(Name = "AFR_MasterHistory", DisableSyncStructure = true)]
public partial class AFRMasterHistory public partial class AFRMasterHistory
{ {
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
@ -19,12 +17,12 @@ namespace djy.Model.Afr
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string AMID { get; set; } public string Operator { get; set; }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public string Operator { get; set; } public string PID { get; set; }
/// <summary> /// <summary>
/// ///
@ -34,7 +32,7 @@ namespace djy.Model.Afr
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public DateTime? SendTime { get; set; } public DateTime? CreateTime { get; set; }
/// <summary> /// <summary>
/// ///
@ -42,10 +40,8 @@ namespace djy.Model.Afr
public string State { get; set; } public string State { get; set; }
/// <summary> /// <summary>
/// /// 日志类型。0人为操作历史 1接收回执历史
/// </summary> /// </summary>
public string Type { get; set; } public byte? Type { get; set; }
} }
} }

@ -10,6 +10,10 @@ namespace djy.Model.AFRDto
/// </summary> /// </summary>
public int Type { get; set; } public int Type { get; set; }
///// <summary>
///// 操作历史查询类型all:全部 latest-people:最新的一条人为操作记录
///// </summary>
//public string HistoryQueryType { get; set; }
/// <summary> /// <summary>
/// 船东提单号 /// 船东提单号
@ -28,6 +32,10 @@ namespace djy.Model.AFRDto
/// </summary> /// </summary>
public DateTime? CreateTimeEnd{ get; set; } public DateTime? CreateTimeEnd{ get; set; }
/// <summary> /// <summary>
/// 船公司
/// </summary>
public string ShipCompany { get; set; }
/// <summary>
/// 操作用户名称 /// 操作用户名称
/// </summary> /// </summary>
public string UserName { get; set; } public string UserName { get; set; }

@ -1,6 +1,6 @@
using Common.DJYModel; using Common.DJYModel;
namespace djy_AfrApi.HttpContextUser namespace djy.Model
{ {
public interface IUser public interface IUser
{ {

@ -1,148 +0,0 @@
using NPOI.SS.Formula.Functions;
namespace djy.Model
{
/// <summary>
/// 通用返回信息类
/// </summary>
public class MessageModel<T>
{
/// <summary>
/// 状态码
/// </summary>
public int code { get; set; } = 200;
/// <summary>
/// 操作是否成功
/// </summary>
public bool success { get; set; } = false;
/// <summary>
/// 返回信息
/// </summary>
public string message { get; set; } = "";
/// <summary>
/// 开发者信息
/// </summary>
public string msgDev { get; set; }
/// <summary>
/// 返回数据集合
/// </summary>
public T data { get; set; }
/// <summary>
/// 返回成功
/// </summary>
/// <param name="msg">消息</param>
/// <returns></returns>
public static MessageModel<T> Success(string msg)
{
return Message(true, msg, default);
}
/// <summary>
/// 返回成功
/// </summary>
/// <param name="msg">消息</param>
/// <param name="data">数据</param>
/// <returns></returns>
public static MessageModel<T> Success(string msg, T data)
{
return Message(true, msg, data);
}
/// <summary>
/// 返回失败
/// </summary>
/// <param name="msg">消息</param>
/// <returns></returns>
public static MessageModel<T> Fail(string msg)
{
return Message(false, msg, default);
}
/// <summary>
/// 返回失败
/// </summary>
/// <param name="msg">消息</param>
/// <param name="data">数据</param>
/// <returns></returns>
public static MessageModel<T> Fail(string msg, T data)
{
return Message(false, msg, data);
}
/// <summary>
/// 返回消息
/// </summary>
/// <param name="success">失败/成功</param>
/// <param name="msg">消息</param>
/// <param name="data">数据</param>
/// <returns></returns>
private static MessageModel<T> Message(bool success, string msg, T data)
{
return new MessageModel<T>() { message = msg, data = data, success = success };
}
}
/// <summary>
///
/// </summary>
public class MessageModel
{
/// <summary>
/// 状态码
/// </summary>
public int code { get; set; } = 200;
/// <summary>
/// 操作是否成功
/// </summary>
public bool success { get; set; } = false;
/// <summary>
/// 返回信息
/// </summary>
public string message { get; set; } = "";
/// <summary>
/// 返回数据集合
/// </summary>
public object data { get; set; }
/// <summary>
/// 返回成功
/// </summary>
/// <param name="msg">消息</param>
/// <returns></returns>
public static MessageModel Success(string msg)
{
return Message(true, msg, default);
}
/// <summary>
/// 返回成功
/// </summary>
/// <param name="msg">消息</param>
/// <param name="data">数据</param>
/// <returns></returns>
public static MessageModel Success(string msg, object data)
{
return Message(true, msg, data);
}
/// <summary>
/// 返回失败
/// </summary>
/// <param name="msg">消息</param>
/// <returns></returns>
public static MessageModel Fail(string msg)
{
return Message(false, msg, default);
}
/// <summary>
/// 返回消息
/// </summary>
/// <param name="success">失败/成功</param>
/// <param name="msg">消息</param>
/// <param name="data">数据</param>
/// <returns></returns>
private static MessageModel Message(bool success, string msg, object data)
{
return new MessageModel() { message = msg, data = data, success = success };
}
}
}

@ -3,10 +3,11 @@
<PropertyGroup> <PropertyGroup>
<TargetFramework>net5.0</TargetFramework> <TargetFramework>net5.0</TargetFramework>
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion> <IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DocumentationFile>bin\Debug\net5.0\djy.Model.xml</DocumentationFile> <DocumentationFile></DocumentationFile>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>

@ -1,23 +1,30 @@
using Common.DJYModel; using Common.DJYModel;
using Common.Extensions;
using Common.Utilities; using Common.Utilities;
using djy.IService.Afr; using djy.IService.Afr;
using djy.Model;
using djy.Model.Afr; using djy.Model.Afr;
using djy.Model.AFRDto; using djy.Model.AFRDto;
using djy.Model.Ams; using djy.Model.Ams;
using djy.Model.AmsDto; using djy.Model.AmsDto;
using djy.Service.DjyService; using djy.Service.DjyService;
using FreeSql.Internal.Model; using FreeSql;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data.Common;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace djy.Service.AFR namespace djy.Service.AFR
{ {
public class AfrService : DbContext, IAfrService public class AfrService : DjyService.DbContext, IAfrService
{ {
private IUser User { get; }
public AfrService(IUser user)
{
User = user;
}
#region 下拉接口 #region 下拉接口
public List<CommonCNEN> GetCountry(string strlink, int page, int limit) public List<CommonCNEN> GetCountry(string strlink, int page, int limit)
{ {
@ -182,46 +189,299 @@ namespace djy.Service.AFR
public async Task<PageModel<AFRMaster>> Load(AFRMasterInputDto input) public async Task<PageModel<AFRMaster>> Load(AFRMasterInputDto input)
{ {
// 查询草稿箱列表 ISelect<AFRMaster> select = null;
// 查询草稿箱列表,草稿箱列表采用一主单内含有多个分单的显示模式
if (input.Type == 1) if (input.Type == 1)
{ {
var select = DbBus.Get(DbList.AMSCenter) select = DbAMS.Select<AFRMaster>();
.Select<AFRMaster>() }
.LeftJoin<AFRHouse>((m, h) => m.GID == h.PID) // 查询已发送列表,已发送列表采用按分单的显示方式
.Where((m) => m.IsDel == false) else if (input.Type == 2)
.WhereIf(!string.IsNullOrEmpty(input.CompanyId), m => m.CompID == input.CompanyId) {
.WhereIf(!string.IsNullOrEmpty(input.UserId), m => m.UserID == input.UserId) select = DbAMS.Select<AFRMaster>()
.WhereIf(!string.IsNullOrEmpty(input.MBLNO), m => m.MBLNO.Contains(input.MBLNO)) .InnerJoin<AFRHouse>((m, h) => m.GID == h.PID);
.WhereIf(!string.IsNullOrEmpty(input.UserName), m => m.UserName.Contains(input.UserName)) }
.WhereIf(!string.IsNullOrEmpty(input.DischargeHarbour), m => m.DischargeHarbour.Contains(input.DischargeHarbour))
.WhereIf(input.CreateTimeStart != null, m => m.CreateTime >= input.CreateTimeStart) select.Where((m) => m.IsDel == false)
.WhereIf(input.CreateTimeEnd != null, m => m.CreateTime <= input.CreateTimeEnd); //下面两个是Controller中传来的条件
.WhereIf(!string.IsNullOrEmpty(input.CompanyId), m => m.CompID == input.CompanyId)
if (!string.IsNullOrEmpty(input.HouseBillNo)) .WhereIf(!string.IsNullOrEmpty(input.UserId), m => m.UserID == input.UserId)
{ // 下面是前端传来的条件
select.Where<AFRHouse>((m, h) => h.HouseBillNo == input.HouseBillNo); .WhereIf(!string.IsNullOrEmpty(input.MBLNO), m => m.MBLNO.Contains(input.MBLNO))
} .WhereIf(!string.IsNullOrEmpty(input.UserName), m => m.UserName.Contains(input.UserName))
List<AFRMaster> result = await select.Page(input) .WhereIf(!string.IsNullOrEmpty(input.DischargeHarbour), m => m.DischargeHarbour.Contains(input.DischargeHarbour))
.IncludeMany(m => m.Houses) .WhereIf(!string.IsNullOrEmpty(input.ShipCompany), m => m.ShipCompany.Contains(input.ShipCompany))
.OrderByDescending(m => m.CreateTime) .WhereIf(input.CreateTimeStart != null, m => m.CreateTime >= input.CreateTimeStart)
.ToListAsync(); .WhereIf(input.CreateTimeEnd != null, m => m.CreateTime <= input.CreateTimeEnd);
return new PageModel<AFRMaster>(input.PageNumber, // 分单上的查询条件在这里实现方式查出分单中的PID作为主单的筛选条件
input.Count, if (!string.IsNullOrEmpty(input.HouseBillNo))
input.PageSize, {
result); var pids = await DbAMS.Select<AFRHouse>()
} .Where(h => h.HouseBillNo.Contains(input.HouseBillNo))
// 查询已发送列表 .ToListAsync(h => h.PID);
select.Where(m => pids.Contains(m.GID));
}
List<AFRMaster> result = await select.IncludeMany(m => m.HouseList, then => then.Where(h => h.IsDel == false))
.Page(input)
.OrderByDescending(m => m.CreateTime)
.ToListAsync();
// 查询操作历史(只查询最新的一条人为操作历史)
if (result.Count > 0)
{
// FreeSql版本较低无法使用嵌套查询所以采用拼sql的方式
var pids = result.Select(m => m.GID);
var pidStr = string.Join("','", pids);
var histories = await DbAMS.Select<AFRMasterHistory>()
.WithSql(@$"SELECT * FROM (
SELECT *,row_number() over ( PARTITION BY Pid ORDER BY {nameof(AFRMasterHistory.CreateTime)} DESC ) AS row_num FROM AFR_MasterHistory WHERE {nameof(AFRMasterHistory.Type)} = 0 AND pid IN ('{pidStr}')) t WHERE row_num =1")
.ToListAsync();
histories.ForEach(item =>
{
var master = result.FirstOrDefault(m => m.GID == item.PID);
if (master == null) return;
master.History = item;
});
}
return new PageModel<AFRMaster>(input.PageNumber,
input.Count,
input.PageSize,
result);
}
public async Task<AFRMaster> Get(string gid)
{
AFRMaster model = await DbAMS.Select<AFRMaster>()
.Where((m) => m.IsDel == false && m.GID == gid)
.IncludeMany(m => m.HouseList, then => then.Where(h => h.IsDel == false)
.IncludeMany(house => house.CntrList))
.FirstAsync();
return model;
}
public async Task SaveInfo(AFRMaster input)
{
int type;
AFRMaster oldMaster = null;
var nowTime = DateTime.Now;
if (string.IsNullOrEmpty(input.GID))
{
type = 0;
}
else else
{ {
return default; oldMaster = await Get(input.GID);
type = oldMaster == null ? 0 : 1;
}
// 新增
if (type == 0)
{
// 将null换为空对象避免后续处理null值麻烦
input.HouseList ??= new List<AFRHouse>();
input.GID = Guid.NewGuid().ToString();
input.UserID = User.GID;
input.UserName = User.ShowName;
input.CompID = User.CompId;
input.CompName = User.CompName;
input.CreateTime = nowTime;
input.HouseList.ForEach(house =>
{
house.GID = Guid.NewGuid().ToString();
house.PID = input.GID;
house.CreateTime = nowTime;
// 将null换为空对象避免后续处理null值麻烦
house.CntrList ??= new List<AFRCntrno>();
house.CntrList.ForEach(cntr =>
{
cntr.GID = Guid.NewGuid().ToString();
cntr.PID = house.GID;
cntr.CreateTime = nowTime;
});
});
await using DbTransaction tran = await GetDbAmsTransaction();
await DbAMS.Insert(input).ExecuteAffrowsAsync();
await DbAMS.Insert(input.HouseList).WithTransaction(tran).ExecuteAffrowsAsync();
await DbAMS.Insert(input.HouseList.SelectMany(h => h.CntrList)).WithTransaction(tran).ExecuteAffrowsAsync();
AFRMasterHistory history = BuildAFRMasterHistory(input.GID, "新增", 0, "创建了单据");
await DbAMS.Insert(history).WithTransaction(tran).ExecuteAffrowsAsync();
tran.Commit();
} }
// 修改
else
{
// 下面这段的3个作用
// 1. 将null换为空对象避免后续处理null值麻烦
// 2. 如果主键为null说明是新加的数据这时候需要手动给GID、PID、CreateTime赋值
// 3. 如果主键不为null说明是修改的数据这时候需要手动给LastUpdate赋值
input.LastUpdate = nowTime;
if (input.HouseList == null)
{
input.HouseList = new List<AFRHouse>();
}
else
{
input.HouseList.ForEach(h =>
{
if (string.IsNullOrEmpty(h.GID))
{
h.GID = Guid.NewGuid().ToString();
h.PID = input.GID;
h.CreateTime = nowTime;
}
else
{
h.LastUpdate = nowTime;
}
//HouseBillNo if (h.CntrList == null)
{
h.CntrList = new List<AFRCntrno>();
}
else
{
h.CntrList.ForEach(c =>
{
if (string.IsNullOrEmpty(c.GID))
{
c.GID = Guid.NewGuid().ToString();
c.PID = h.GID;
c.CreateTime = nowTime;
}
else
{
c.LastUpdate = nowTime;
}
});
}
});
}
#region 对分单数据统计出要执行的操作,判断哪些数据是 新增/修改/删除
var inputHouseGids = input.HouseList?.Select(h => h.GID);
var oldHouseGids = oldMaster.HouseList?.Select(h => h.GID);
var waitInsertHouseGids = inputHouseGids.Except(oldHouseGids); // 要新增的分单主键
var waitDeleteHouseGids = oldHouseGids.Except(inputHouseGids); // 要删除的分单主键
var waitUpdateHouseGids = oldHouseGids.Intersect(inputHouseGids); // 要修改的分单主键
List<AFRHouse> waitInsertHouseList = null, waitUpdateHouseList = null;
if (waitInsertHouseGids.Any())
{
waitInsertHouseList = input.HouseList.Where(h => waitInsertHouseGids.Contains(h.GID)).ToList();
}
if (waitUpdateHouseGids.Any())
{
waitUpdateHouseList = input.HouseList.Where(h => waitUpdateHouseGids.Contains(h.GID)).ToList();
}
#endregion
#region 对箱子数据统计出要执行的操作,判断哪些数据是 新增/修改/删除
var inputCtnList = input.HouseList.SelectMany(h => h.CntrList);
var oldCtnList = oldMaster.HouseList.SelectMany(h => h.CntrList);
var inputCtnGids = inputCtnList.Select(ctn => ctn.GID);
var oldCtnGids = oldCtnList.Select(ctn => ctn.GID);
var waitInsertCtnGids = inputCtnGids.Except(oldCtnGids); // 要新增的箱子主键
var waitDeleteCtnGids = oldCtnGids.Except(inputCtnGids); // 要删除的箱子主键
var waitUpdateCtnGids = oldCtnGids.Intersect(inputCtnGids); // 要修改的箱子主键
List<AFRCntrno> waitInsertCtnList = null, waitUpdateCtnList = null;
if (waitInsertCtnGids.Any())
{
waitInsertCtnList = inputCtnList.Where(c => waitInsertCtnGids.Contains(c.GID)).ToList();
}
if (waitUpdateCtnGids.Any())
{
waitUpdateCtnList = inputCtnList.Where(c => waitUpdateCtnGids.Contains(c.GID)).ToList();
}
#endregion
#region 开始执行
await using DbTransaction tran = await GetDbAmsTransaction();
// 主单执行
await DbAMS.Update<AFRMaster>()
.SetSource(input)
.IgnoreColumns(m => new { m.CompID, m.CompName, m.UserID, m.UserName })
.WithTransaction(tran)
.ExecuteAffrowsAsync();
// 分单执行
if (waitInsertHouseGids.Any())
{
await DbAMS.Insert(waitInsertHouseList).WithTransaction(tran).ExecuteAffrowsAsync();
}
if (waitDeleteHouseGids.Any())
{
await DbAMS.Update<AFRHouse>()
.Set(h => h.IsDel == true)
.Set(h => h.LastUpdate == nowTime)
.WithTransaction(tran)
.Where(h => waitDeleteHouseGids.Contains(h.GID))
.ExecuteAffrowsAsync();
}
if (waitUpdateHouseGids.Any())
{
await DbAMS.Update<AFRHouse>()
.SetSource(waitUpdateHouseList)
.IgnoreColumns(h => new { h.StateIsMatched, h.StateIsAccept })
.WithTransaction(tran)
.ExecuteAffrowsAsync();
}
// 箱子执行
if (waitInsertCtnGids.Any())
{
await DbAMS.Insert(waitInsertCtnList).WithTransaction(tran).ExecuteAffrowsAsync();
}
if (waitDeleteCtnGids.Any())
{
await DbAMS.Delete<AFRCntrno>()
.WithTransaction(tran)
.Where(h => waitDeleteCtnGids.Contains(h.GID))
.ExecuteAffrowsAsync();
}
if (waitUpdateCtnGids.Any())
{
await DbAMS.Update<AFRCntrno>()
.SetSource(waitUpdateCtnList)
.WithTransaction(tran)
.ExecuteAffrowsAsync();
}
#endregion
AFRMasterHistory history = BuildAFRMasterHistory(input.GID, "修改", 0, "修改了单据");
await DbAMS.Insert(history).WithTransaction(tran).ExecuteAffrowsAsync();
tran.Commit();
}
} }
public Task SaveInfo(AFRMasterDto input)
private AFRMasterHistory BuildAFRMasterHistory(string pid, string state, int type, string remark)
{ {
throw new NotImplementedException(); var history = new AFRMasterHistory()
{
GID = Guid.NewGuid().ToString(),
CreateTime = DateTime.Now,
Operator = User.ShowName,
PID = pid,
State = state,
Type = Convert.ToByte(type)
};
history.Remark = $"{history.Operator}于{history.CreateTime}{remark}";
return history;
} }
public Task Delete(string ids) public Task Delete(string ids)
@ -238,5 +498,6 @@ namespace djy.Service.AFR
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
} }
} }

@ -1,10 +1,11 @@
using Common.DJYModel; using Common.DJYModel;
using djy.IService.Djy; using djy.IService.Djy;
using djy.Model;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using System; using System;
using System.Linq; using System.Linq;
namespace djy_AfrApi.HttpContextUser namespace djy.Service.DjyService
{ {
public class AspNetUser : IUser public class AspNetUser : IUser
{ {
@ -34,7 +35,7 @@ namespace djy_AfrApi.HttpContextUser
return userTemp.Data; return userTemp.Data;
} }
throw new Exception("获取当前登录用户时发生异常"); throw new Exception("登录失效");
} }
} }
public string CompId => CurrentUser.CompId; public string CompId => CurrentUser.CompId;

@ -1,16 +1,13 @@
using FreeRedis; using Common;
using FreeRedis.Internal; using Common.Helpers;
using FreeRedis;
using FreeSql; using FreeSql;
using FreeSql.Internal.ObjectPool;
using System; using System;
using System.Collections.Generic; using System.Data.Common;
using System.Diagnostics; using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Common;
using System.Data;
using Common.Helpers;
namespace djy.Service.DjyService namespace djy.Service.DjyService
{ {
@ -57,6 +54,16 @@ namespace djy.Service.DjyService
/// </summary> /// </summary>
public static IdleBus<IFreeSql> DbBus = new IdleBus<IFreeSql>(TimeSpan.FromSeconds(20)); public static IdleBus<IFreeSql> DbBus = new IdleBus<IFreeSql>(TimeSpan.FromSeconds(20));
public static IFreeSql DbAMS => DbBus.Get(DbList.AMSCenter);
public async Task<DbTransaction> GetDbAmsTransaction()
{
Object<DbConnection> conn = await DbAMS.Ado.MasterPool.GetAsync();
DbTransaction transaction = await conn.Value.BeginTransactionAsync();
return transaction;
}
/// <summary> /// <summary>
/// RedisDB /// RedisDB
/// </summary> /// </summary>
@ -106,7 +113,7 @@ namespace djy.Service.DjyService
}); });
}; };
} }
return freeSql; return freeSql;
}); });
} }

@ -0,0 +1,9 @@
using System;
namespace djy_AfrApi.Attributes
{
[AttributeUsage(AttributeTargets.Method)]
public class RedisCachingAttribute : Attribute
{
}
}

@ -1,39 +1,33 @@
using Common.DJYModel; using Common.DJYModel;
using Common.Utilities; using Common.Utilities;
using djy.IService.Afr; using djy.IService.Afr;
using djy.Model;
using djy.Model.Afr; using djy.Model.Afr;
using djy.Model.AFRDto; using djy.Model.AFRDto;
using djy.Model.IsfDto;
using djy_AfrApi.HttpContextUser;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Org.BouncyCastle.Crypto;
using System; using System;
using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace djy_AfrApi.Controllers namespace djy_AfrApi.Controllers
{ {
/// <summary>
/// AFR对接接口
/// </summary>
[Route("api/[controller]")] [Route("api/[controller]")]
[ApiController] [ApiController]
[Authorize] [Authorize]
public class AfrController : ApiBase public class AfrController : ApiBase
{ {
private readonly ILogger logger; private readonly ILogger logger;
private readonly IUser user;
private readonly IAfrService _afrService; private readonly IAfrService _afrService;
//private readonly ILogger bigLogger; //private readonly ILogger bigLogger;
public AfrController(ILogger<AfrController> logger, public AfrController(ILogger<AfrController> logger,
IUser user,
IAfrService afrService) IAfrService afrService)
{ {
this.logger = logger; this.logger = logger;
this.user = user;
this._afrService = afrService; this._afrService = afrService;
// 获取ILogger对象 // 获取ILogger对象
@ -42,6 +36,11 @@ namespace djy_AfrApi.Controllers
} }
#region 查询接口 #region 查询接口
/// <summary>
/// 分页查询草稿箱或已发送列表的数据
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[HttpGet("PageData")] [HttpGet("PageData")]
public async Task<ResponsePage<AFRMaster>> PageData(AFRMasterInputDto input) public async Task<ResponsePage<AFRMaster>> PageData(AFRMasterInputDto input)
{ {
@ -53,9 +52,25 @@ namespace djy_AfrApi.Controllers
var pageData = await _afrService.Load(input); var pageData = await _afrService.Load(input);
return SuccessPage(pageData); return SuccessPage(pageData);
} }
/// <summary>
/// 获取详情
/// </summary>
/// <param name="gid"></param>
/// <returns></returns>
[HttpGet("Get")]
public async Task<Response<AFRMaster>> Get(string gid)
{
var model = await _afrService.Get(gid);
return SuccessResp(model);
}
#endregion #endregion
#region 新增/编辑 #region 新增/编辑
/// <summary>
/// 新增或修改
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[HttpPost("AddOrUpdate")] [HttpPost("AddOrUpdate")]
public async Task<Response> AddOrUpdateAsync([FromBody] AFRMasterDto input) public async Task<Response> AddOrUpdateAsync([FromBody] AFRMasterDto input)
{ {
@ -65,6 +80,11 @@ namespace djy_AfrApi.Controllers
#endregion #endregion
#region 删除 #region 删除
/// <summary>
/// 删除
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
[HttpPost("Del")] [HttpPost("Del")]
public async Task<Response> Delete(string ids) public async Task<Response> Delete(string ids)
{ {
@ -74,6 +94,12 @@ namespace djy_AfrApi.Controllers
#endregion #endregion
#region 第三方接口 #region 第三方接口
/// <summary>
/// 发送接口
/// </summary>
/// <param name="ids"></param>
/// <param name="msgType"></param>
/// <returns></returns>
[HttpGet("Send")] [HttpGet("Send")]
public async Task<Response> Send(string ids, string msgType) public async Task<Response> Send(string ids, string msgType)
{ {
@ -81,6 +107,11 @@ namespace djy_AfrApi.Controllers
return SuccessResp(); return SuccessResp();
} }
/// <summary>
/// 接收回执
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[AllowAnonymous] [AllowAnonymous]
[HttpPost("Receipt")] [HttpPost("Receipt")]
public async Task<Response> SaveReceiptAsync(AFRReceiptDto input) public async Task<Response> SaveReceiptAsync(AFRReceiptDto input)
@ -89,7 +120,10 @@ namespace djy_AfrApi.Controllers
return SuccessResp("接收成功"); return SuccessResp("接收成功");
} }
#endregion #endregion
/// <summary>
/// 获取服务器当前时间
/// </summary>
/// <returns></returns>
[AllowAnonymous] [AllowAnonymous]
[HttpGet("[action]")] [HttpGet("[action]")]
public Response GetTime() public Response GetTime()

@ -21,6 +21,11 @@ namespace djy_AfrApi.Controllers
[NonAction] [NonAction]
protected ResponsePage<T> SuccessPage<T>(PageModel<T> pageModel) protected ResponsePage<T> SuccessPage<T>(PageModel<T> pageModel)
{ {
if (pageModel is null)
{
throw new ArgumentNullException(nameof(pageModel));
}
return new ResponsePage<T>() return new ResponsePage<T>()
{ {
Code = 200, Code = 200,
@ -40,6 +45,16 @@ namespace djy_AfrApi.Controllers
Message = message Message = message
}; };
} }
[NonAction]
protected Response<T> SuccessResp<T>(T result)
{
return new Response<T>()
{
Code = 200,
Message = "操作成功",
Result = result
};
}
#endregion #endregion

@ -1,23 +1,33 @@
using Common; using Common.Utilities;
using Common.Utilities;
using djy.IService.Afr; using djy.IService.Afr;
using djy.Model.AmsDto; using djy.Model.AmsDto;
using djy_AfrApi.Attributes;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace djy_AfrApi.Controllers.Common namespace djy_AfrApi.Controllers.Common
{ {
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class CommonController public class CommonController
{ {
IAfrService ser = IOC.AddServer<IAfrService>(); private readonly IAfrService ser;
public CommonController(IAfrService service)
{
this.ser = service;
}
#region 下拉接口 #region 下拉接口
/// <summary> /// <summary>
/// 下拉获取国家 /// 下拉获取国家
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[HttpGet("GetCountry")] [HttpGet("GetCountry")]
[RedisCaching]
public Response<List<CommonCNEN>> GetCountry(string strlink = "", int page = 0, int limit = 0) public Response<List<CommonCNEN>> GetCountry(string strlink = "", int page = 0, int limit = 0)
{ {
var result = new Response<List<CommonCNEN>>(); var result = new Response<List<CommonCNEN>>();
@ -39,6 +49,7 @@ namespace djy_AfrApi.Controllers.Common
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[HttpGet("GetCARRIER")] [HttpGet("GetCARRIER")]
[RedisCaching]
public Response<List<CommonMappiCode>> GetCARRIER() public Response<List<CommonMappiCode>> GetCARRIER()
{ {
var result = new Response<List<CommonMappiCode>>(); var result = new Response<List<CommonMappiCode>>();
@ -59,6 +70,7 @@ namespace djy_AfrApi.Controllers.Common
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[HttpGet("GetCTNALL")] [HttpGet("GetCTNALL")]
[RedisCaching]
public Response<List<CommonCodeValue>> GetCTNALL() public Response<List<CommonCodeValue>> GetCTNALL()
{ {
var result = new Response<List<CommonCodeValue>>(); var result = new Response<List<CommonCodeValue>>();
@ -81,6 +93,7 @@ namespace djy_AfrApi.Controllers.Common
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[HttpGet("GetPackage")] [HttpGet("GetPackage")]
[RedisCaching]
public Response<List<CommonCodeValue>> GetPackage() public Response<List<CommonCodeValue>> GetPackage()
{ {
var result = new Response<List<CommonCodeValue>>(); var result = new Response<List<CommonCodeValue>>();
@ -101,6 +114,7 @@ namespace djy_AfrApi.Controllers.Common
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[HttpGet("GetDangerousGoods")] [HttpGet("GetDangerousGoods")]
[RedisCaching]
public Response<List<CodeDangerGradeDto>> GetDangerousGoods(string strlink = "",int page = 0, int limit = 0) public Response<List<CodeDangerGradeDto>> GetDangerousGoods(string strlink = "",int page = 0, int limit = 0)
{ {
var result = new Response<List<CodeDangerGradeDto>>(); var result = new Response<List<CodeDangerGradeDto>>();
@ -143,6 +157,7 @@ namespace djy_AfrApi.Controllers.Common
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[HttpGet("GetPort")] [HttpGet("GetPort")]
[RedisCaching]
public Response<List<CommonCodeValue>> GetPort(string strlink = "", int page = 0, int limit = 0) public Response<List<CommonCodeValue>> GetPort(string strlink = "", int page = 0, int limit = 0)
{ {
var result = new Response<List<CommonCodeValue>>(); var result = new Response<List<CommonCodeValue>>();
@ -164,6 +179,7 @@ namespace djy_AfrApi.Controllers.Common
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[HttpGet("GetVessel")] [HttpGet("GetVessel")]
[RedisCaching]
public Response<List<CommonCodeValue>> GetVessel(string strlink = "", int page = 0,int limit =0) public Response<List<CommonCodeValue>> GetVessel(string strlink = "", int page = 0,int limit =0)
{ {
var result = new Response<List<CommonCodeValue>>(); var result = new Response<List<CommonCodeValue>>();

@ -1,33 +0,0 @@
--------------------------------
2023/12/27 15:41:20|
ManagedThreadId:19; FullName:djy.Model.Afr.AFRMaster ElapsedMilliseconds:30ms
SELECT count(1) as1
FROM [AFR_Master] a
LEFT JOIN [AFR_House] h ON a.[GID] = h.[PID]
WHERE (a.[IsDel] = 0) AND ((a.[UserName]) LIKE N'%朱洋%') AND (a.[CreateTime] >= '1991-04-18 21:23:40.000') AND (a.[CreateTime] <= '1988-04-22 20:14:18.000') AND (h.[HouseBillNo] = N'sunt laborum')
--------------------------------
2023/12/27 15:42:50|
ManagedThreadId:7; FullName:djy.Model.Afr.AFRMaster ElapsedMilliseconds:44ms
SELECT count(1) as1
FROM [AFR_Master] a
LEFT JOIN [AFR_House] h ON a.[GID] = h.[PID]
WHERE (a.[IsDel] = 0) AND ((a.[UserName]) LIKE N'%朱洋%') AND (a.[CreateTime] >= '1991-04-18 21:23:40.000') AND (a.[CreateTime] <= '1988-04-22 20:14:18.000') AND (h.[HouseBillNo] = N'sunt laborum')
--------------------------------
2023/12/27 15:45:04|
ManagedThreadId:12; FullName:djy.Model.Afr.AFRMaster ElapsedMilliseconds:46ms
SELECT count(1) as1
FROM [AFR_Master] a
LEFT JOIN [AFR_House] h ON a.[GID] = h.[PID]
WHERE (a.[IsDel] = 0) AND ((a.[UserName]) LIKE N'%朱洋%') AND (a.[CreateTime] >= '1991-04-18 21:23:40.000') AND (a.[CreateTime] <= '1988-04-22 20:14:18.000') AND (h.[HouseBillNo] = N'sunt laborum')
--------------------------------
2023/12/27 15:45:04|
ManagedThreadId:5; FullName:djy.Model.Afr.AFRMaster ElapsedMilliseconds:330ms
SELECT TOP 10 a.[GID], a.[UserID], a.[UserName], a.[CompID], a.[CompName], a.[IsDel], a.[LastUpdate], a.[CreateTime], a.[Clause], a.[ConsignmentType], a.[DischargeHarbour], a.[DischargeHarbourCode], a.[EstimatedArrivalTime], a.[FilingType], a.[LastForeignHarbour], a.[LastForeignHarbourCode], a.[LoadDate], a.[LoadHarbour], a.[LoadHarbourCode], a.[MBLNO], a.[ShipCompany], a.[ShippingNo], a.[Vessel], a.[Voyno]
FROM [AFR_Master] a
LEFT JOIN [AFR_House] h ON a.[GID] = h.[PID]
WHERE (a.[IsDel] = 0) AND ((a.[UserName]) LIKE N'%朱洋%') AND (a.[CreateTime] >= '1991-04-18 21:23:40.000') AND (a.[CreateTime] <= '1988-04-22 20:14:18.000') AND (h.[HouseBillNo] = N'sunt laborum')
ORDER BY a.[CreateTime] DESC

@ -0,0 +1,85 @@
using Common.Tools;
using Common.Utilities;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Controllers;
using Newtonsoft.Json;
using System.Diagnostics;
using System;
using System.IO;
using System.Threading.Tasks;
using NPOI.XWPF.UserModel;
using djy_AfrApi.Attributes;
namespace djy_AfrApi.Milldlewares
{
public class CommonCacheMiddleware
{
private readonly RequestDelegate next;
public CommonCacheMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task InvokeAsync(HttpContext context)
{
var endpoint = context.GetEndpoint();
if (endpoint?.Metadata?.GetMetadata<RedisCachingAttribute>() == null)
{
await next(context);
}
else
{
var actionDescriptor = endpoint.Metadata.GetMetadata<ControllerActionDescriptor>();
if (actionDescriptor?.ActionName == null)
{
await next(context);
}
else
{
string redisKey = actionDescriptor.ActionName + "Cache";
string cacheData = YsRedisHelp.RedisGetString(redisKey);
if (string.IsNullOrEmpty(cacheData))
{
// 存储响应数据
using (MemoryStream memoryStream = new MemoryStream())
{
// 使用自定义的响应流,将所有写入重定向到内存流
var originalBodyStream = context.Response.Body;
context.Response.Body = memoryStream;
try
{
await next(context);
// 从内存流读取响应内容
memoryStream.Seek(0, SeekOrigin.Begin);
string responseBody = new StreamReader(memoryStream).ReadToEnd();
Response response = JsonConvert.DeserializeObject<Response>(responseBody);
if (response.Code == 200)
{
YsRedisHelp.RedisSet<string>(redisKey, responseBody, 86400);
}
// 将响应内容写回原始响应流
memoryStream.Seek(0, SeekOrigin.Begin);
await memoryStream.CopyToAsync(originalBodyStream);
}
finally
{
// 恢复原始响应流
context.Response.Body = originalBodyStream;
}
}
}
else
{
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(cacheData).ConfigureAwait(false);
}
}
}
}
}
}

@ -29,10 +29,20 @@ namespace djy_AfrApi.Middlewares
return app.UseMiddleware<NextAuthorizationMiddleware>(); return app.UseMiddleware<NextAuthorizationMiddleware>();
} }
// 记录请求和响应数据 /// <summary>
/// 记录请求和响应数据
/// </summary>
public static IApplicationBuilder UseRequRespLogMiddleware(this IApplicationBuilder app) public static IApplicationBuilder UseRequRespLogMiddleware(this IApplicationBuilder app)
{ {
return app.UseMiddleware<RequRespLogMiddleware>(); return app.UseMiddleware<RequRespLogMiddleware>();
} }
/// <summary>
/// 公共数据缓存中间件
/// </summary>
public static IApplicationBuilder UseCommonCacheMiddleware(this IApplicationBuilder app)
{
return app.UseMiddleware<CommonCacheMiddleware>();
}
} }
} }

@ -22,7 +22,8 @@ namespace djy_AfrApi.Milldlewares
} }
public async Task InvokeAsync(HttpContext context) public async Task InvokeAsync(HttpContext context)
{ {
if (context.Request.Path.Value.Contains("api")) // 字典接口不记录日志
if (context.Request.Path.Value.Contains("api") && !context.Request.Path.Value.Contains("/api/Common/"))
{ {
_stopwatch.Restart(); _stopwatch.Restart();
@ -31,9 +32,9 @@ namespace djy_AfrApi.Milldlewares
//// 存储请求数据 //// 存储请求数据
var request = context.Request; var request = context.Request;
var sr = new StreamReader(request.Body); var sr = new StreamReader(request.Body);
var bodyData = await sr.ReadToEndAsync(); var bodyData = await sr.ReadToEndAsync();
_logger.LogInformation($"请求 - {context.TraceIdentifier}{Environment.NewLine}[Path]:{request.Path} [QueryString]:{request.QueryString}{Environment.NewLine}[Body]:{bodyData}"); _logger.LogInformation($"请求 - {context.TraceIdentifier}{Environment.NewLine}[Path]:{request.Path} [QueryString]:{request.QueryString}{Environment.NewLine}[Body]:{bodyData}");
request.Body.Position = 0; request.Body.Position = 0;

@ -2,7 +2,6 @@
"profiles": { "profiles": {
"djy_AfrApi": { "djy_AfrApi": {
"commandName": "Project", "commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger", "launchUrl": "swagger",
"environmentVariables": { "environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development" "ASPNETCORE_ENVIRONMENT": "Development"

@ -1,7 +1,7 @@
using Common; using Common;
using djy.Model;
using djy.Service.DjyService; using djy.Service.DjyService;
using djy_AfrApi.Filter; using djy_AfrApi.Filter;
using djy_AfrApi.HttpContextUser;
using djy_AfrApi.Middlewares; using djy_AfrApi.Middlewares;
using FreeRedis; using FreeRedis;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
@ -15,6 +15,8 @@ using Microsoft.OpenApi.Models;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Converters; using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Serialization;
using System.IO;
using System;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
@ -102,7 +104,17 @@ namespace djy_AfrApi
services.AddSwaggerGen(c => services.AddSwaggerGen(c =>
{ {
c.SwaggerDoc("v1", new OpenApiInfo { Title = "djy_AfrApi", Version = "v1" }); c.SwaggerDoc("v1", new OpenApiInfo { Title = "AFR Api文档", Version = "v1" });
var basePath = AppContext.BaseDirectory;
var xmlPath = Path.Combine(basePath, "djy_AfrApi.xml");
c.IncludeXmlComments(xmlPath, true);
var xmlModelPath = Path.Combine(basePath, "djy.Model.xml");
c.IncludeXmlComments(xmlModelPath);
c.UseInlineDefinitionsForEnums();
}); });
IOC.container = services; IOC.container = services;
} }
@ -114,7 +126,7 @@ namespace djy_AfrApi
{ {
app.UseDeveloperExceptionPage(); app.UseDeveloperExceptionPage();
app.UseSwagger(); app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "djy_AfrApi v1")); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "AFR Api文档 v1"));
} }
// 记录请求响应数据 // 记录请求响应数据
app.UseRequRespLogMiddleware(); app.UseRequRespLogMiddleware();
@ -152,6 +164,9 @@ namespace djy_AfrApi
// 二次验证授权并保存当前登录人User对象为了和ISF、AMS逻辑保持一致 // 二次验证授权并保存当前登录人User对象为了和ISF、AMS逻辑保持一致
app.UseNextAuthorizationMiddle(); app.UseNextAuthorizationMiddle();
// 公共字典数据缓存中间件
app.UseCommonCacheMiddleware();
app.UseEndpoints(endpoints => app.UseEndpoints(endpoints =>
{ {
endpoints.MapControllers(); endpoints.MapControllers();

@ -3,6 +3,7 @@
<PropertyGroup> <PropertyGroup>
<TargetFramework>net5.0</TargetFramework> <TargetFramework>net5.0</TargetFramework>
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion> <IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>

Loading…
Cancel
Save