Browse Source

0523

master
wxd 5 months ago
parent
commit
23152a1db2
  1. 1
      Shentun.PeisReport.Api/Controllers/PeisController.cs
  2. 255
      Shentun.PeisReport.Api/Controllers/ReportBusinessController.cs
  3. 3
      Shentun.PeisReport.Api/Controllers/ReportController.cs
  4. 33
      Shentun.PeisReport.Api/Controllers/WeatherForecastController.cs
  5. 41
      Shentun.PeisReport.Api/Dto/ReportBusiness/GetLisReportByIdNoDto.cs
  6. 15
      Shentun.PeisReport.Api/Dto/ReportBusiness/GetLisReportByIdNoInputDto.cs
  7. 46
      Shentun.PeisReport.Api/Dto/ReportBusiness/GetPeisReportByIdNoDto.cs
  8. 15
      Shentun.PeisReport.Api/Dto/ReportBusiness/GetPeisReportByIdNoInputDto.cs
  9. 47
      Shentun.PeisReport.Api/Jwt/JwtConfig.cs
  10. 85
      Shentun.PeisReport.Api/Jwt/JwtHelper.cs
  11. 61
      Shentun.PeisReport.Api/Program.cs
  12. 1
      Shentun.PeisReport.Api/Shentun.PeisReport.Api.csproj
  13. 13
      Shentun.PeisReport.Api/WeatherForecast.cs
  14. 18
      Shentun.PeisReport.Api/appsettings.json

1
Shentun.PeisReport.Api/Controllers/PeisController.cs

@ -10,6 +10,7 @@ namespace Shentun.PeisReport.Api.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
[ApiExplorerSettings(GroupName = "QingHaiWuYuanApi")]
public class PeisController : ControllerBase
{
private readonly SqlSugarClient _peisDb;

255
Shentun.PeisReport.Api/Controllers/ReportBusinessController.cs

@ -0,0 +1,255 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Shentun.PeisReport.Api.Dto;
using Shentun.PeisReport.Api.Dto.ReportBusiness;
using Shentun.PeisReport.Api.Jwt;
using SqlSugar;
using System.Data;
using System.Security.Claims;
namespace Shentun.PeisReport.Api.Controllers
{
/// <summary>
/// 监利医院
/// </summary>
[Route("api/[controller]/[action]")]
[ApiController]
[ApiExplorerSettings(GroupName ="JianLiApi")]
//[Authorize]
public class ReportBusinessController : ControllerBase
{
private readonly SqlSugarClient _peisDb;
private readonly SqlSugarClient _lisDb;
private readonly IConfiguration _configuration;
private readonly ILogger<ReportBusinessController> _logger;
/// <summary>
///
/// </summary>
public ReportBusinessController(
ILogger<ReportBusinessController> logger,
IConfiguration configuration
)
{
_logger = logger;
_configuration = configuration;
_peisDb = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = _configuration.GetSection("ConnectionStrings:Default").Value,
DbType = SqlSugar.DbType.SqlServer,
IsAutoCloseConnection = true
});
_lisDb = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = _configuration.GetSection("ConnectionStrings:Lis").Value,
DbType = SqlSugar.DbType.SqlServer,
IsAutoCloseConnection = true
});
}
/// <summary>
/// 根据身份证号码获取体检报告
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[HttpPost]
public async Task<GetPeisReportByIdNoDto> GetPeisReportByIdNoAsync(GetPeisReportByIdNoInputDto input)
{
var result = new GetPeisReportByIdNoDto
{
Code = 100,
Message = "请求失败"
};
if (string.IsNullOrWhiteSpace(input.IdNo))
{
result.Message = "身份证不能为空";
return result;
}
try
{
var query = await _peisDb.Ado.GetDataTableAsync($"select top {input.ReportCount} patient_register_id,barcode_no,medical_times,id_card_no," +
$"medical_start_date,mobile_telephone,name as patient_name" +
$" from patient_register " +
$" where id_card_no='{input.IdNo}' and create_pdf_flag='1' order by patient_register_id desc ");
if (query.Rows.Count > 0)
{
List<GetPeisReportByIdNoResultDataDto> patientRegisterList = new List<GetPeisReportByIdNoResultDataDto>();
foreach (DataRow row in query.Rows)
{
var patientRegister = new GetPeisReportByIdNoResultDataDto
{
BarcodeNo = row["barcode_no"].ToString(),
MedicalDate = Convert.ToDateTime(row["medical_start_date"].ToString()).ToString("yyyy-MM-dd"),
MedicalTimes = row["medical_times"].ToString(),
MobileTelephone = row["mobile_telephone"].ToString(),
PatientName = row["patient_name"].ToString(),
IdNo = row["id_card_no"].ToString()
};
var patientRegisterId = row["patient_register_id"].ToString();
string directoryDate = patientRegisterId.Substring(0, 6);
string hostAddress = _configuration.GetSection("HostAddress").Value;
string reportVirtual = _configuration.GetSection("ReportVirtualPath:RequestPath").Value;
string reportUrl = $"{hostAddress + reportVirtual}/{directoryDate}/{patientRegisterId}({patientRegister.PatientName}).pdf";
patientRegister.ReportUrl = reportUrl;
patientRegisterList.Add(patientRegister);
}
result.Message = "请求成功";
result.Data = patientRegisterList;
result.Code = 200;
}
else
{
result.Code = 100;
result.Message = "身份证号未查到体检数据";
}
}
catch (Exception ex)
{
result.Message = ex.Message;
_logger.LogError($"访问GetPeisReportByIdNoAsync异常,异常信息:{ex.Message}");
}
return result;
}
/// <summary>
/// 根据身份证号码获取检验报告
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[HttpPost]
public async Task<GetLisReportByIdNoDto> GetLisReportByIdNoAsync(GetLisReportByIdNoInputDto input)
{
var result = new GetLisReportByIdNoDto
{
Code = 100,
Message = "请求失败"
};
if (string.IsNullOrWhiteSpace(input.IdNo))
{
result.Message = "身份证不能为空";
return result;
}
try
{
var query = await _lisDb.Ado.GetDataTableAsync($" select patient_register_id,patient_name,inspection_purpose,telephone,send_datetime from patient_register" +
$" where upload_web_flag='Y' and inspection_datetime>= DATEADD(DAY,-{input.ReportDay},GETDATE()) " +
$" and recieve_source_primarykey in " +
$" (select recieve_source_primarykey from patient_request where id_card_no='{input.IdNo}' ) order by patient_register_id desc ");
if (query.Rows.Count > 0)
{
List<GetLisReportByIdNoResultDataDto> patientRegisterList = new List<GetLisReportByIdNoResultDataDto>();
foreach (DataRow row in query.Rows)
{
var patientRegister = new GetLisReportByIdNoResultDataDto
{
InspectionPurpose = row["inspection_purpose"].ToString(),
SendDateTime = Convert.ToDateTime(row["send_datetime"].ToString()).ToString("yyyy-MM-dd"),
MobileTelephone = row["telephone"].ToString(),
PatientName = row["patient_name"].ToString(),
IdNo = input.IdNo
};
var patientRegisterId = row["patient_register_id"].ToString();
string hostAddress = _configuration.GetSection("HostAddress").Value;
string reportVirtual = _configuration.GetSection("LisReportVirtualPath:RequestPath").Value;
string reportUrl = $"{hostAddress + reportVirtual}/{patientRegisterId}.pdf";
patientRegister.ReportUrl = reportUrl;
patientRegisterList.Add(patientRegister);
}
result.Message = "请求成功";
result.Data = patientRegisterList;
result.Code = 200;
}
else
{
result.Code = 100;
result.Message = "身份证号未查到检验报告数据";
}
}
catch (Exception ex)
{
result.Message = ex.Message;
_logger.LogError($"访问GetLisReportByIdNoAsync异常,异常信息:{ex.Message}");
}
return result;
}
#region 身份验证
///// <summary>
///// 登陆
///// </summary>
///// <returns></returns>
//[HttpPost]
//[AllowAnonymous]
//public ActionResult<string> Logon()
//{
// var userId = "001";
// var userName = "wenxiande";
// var roleName = "Bus";
// var claims = new List<Claim>()
// {
// new Claim("UserId",userId),
// new Claim(ClaimTypes.Sid,userId),
// new Claim("UserName",userName),
// new Claim(ClaimTypes.Name,userName)
// };
// claims.Add(new Claim(ClaimTypes.Role, roleName));
// JwtHelper jwtHelper = new JwtHelper();
// return jwtHelper.GetJwt(claims);
//}
///// <summary>
///// 查询测试
///// </summary>
///// <returns></returns>
//[HttpPost]
//[Authorize(Roles = "Bus")]
//public PublicResultDto TestSqlAsync()
//{
// var result = new PublicResultDto
// {
// Code = 200,
// Message = "请求成功"
// };
// return result;
//}
#endregion
}
}

3
Shentun.PeisReport.Api/Controllers/ReportController.cs

@ -10,10 +10,11 @@ using static Dm.net.buffer.ByteArrayBuffer;
namespace Shentun.PeisReport.Api.Controllers
{
/// <summary>
/// 上传
/// 青海五院数据上传接口
/// </summary>
[Route("api/[controller]/[action]")]
[ApiController]
[ApiExplorerSettings(GroupName = "QingHaiWuYuanApi")]
public class ReportController : ControllerBase
{
private readonly SqlSugarClient _peisDb;

33
Shentun.PeisReport.Api/Controllers/WeatherForecastController.cs

@ -1,33 +0,0 @@
using Microsoft.AspNetCore.Mvc;
namespace Shentun.PeisReport.Api.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}

41
Shentun.PeisReport.Api/Dto/ReportBusiness/GetLisReportByIdNoDto.cs

@ -0,0 +1,41 @@
namespace Shentun.PeisReport.Api.Dto.ReportBusiness
{
public class GetLisReportByIdNoDto : PublicResultDto
{
public List<GetLisReportByIdNoResultDataDto> Data { get; set; } = new List<GetLisReportByIdNoResultDataDto>();
}
public class GetLisReportByIdNoResultDataDto
{
/// <summary>
/// 检验目的
/// </summary>
public string InspectionPurpose { get; set; }
/// <summary>
/// 姓名
/// </summary>
public string PatientName { get; set; }
/// <summary>
/// 身份证号码
/// </summary>
public string IdNo { get; set; }
/// <summary>
/// 手机号
/// </summary>
public string MobileTelephone { get; set; }
/// <summary>
/// 报告发布时间
/// </summary>
public string SendDateTime { get; set; }
/// <summary>
/// 报告地址
/// </summary>
public string ReportUrl { get; set; }
}
}

15
Shentun.PeisReport.Api/Dto/ReportBusiness/GetLisReportByIdNoInputDto.cs

@ -0,0 +1,15 @@
namespace Shentun.PeisReport.Api.Dto.ReportBusiness
{
public class GetLisReportByIdNoInputDto
{
/// <summary>
/// 身份证号码
/// </summary>
public string IdNo { get; set; }
/// <summary>
/// 查询报告的时间 单位为天 默认30天
/// </summary>
public int ReportDay { get; set; } = 30;
}
}

46
Shentun.PeisReport.Api/Dto/ReportBusiness/GetPeisReportByIdNoDto.cs

@ -0,0 +1,46 @@
namespace Shentun.PeisReport.Api.Dto.ReportBusiness
{
public class GetPeisReportByIdNoDto: PublicResultDto
{
public List<GetPeisReportByIdNoResultDataDto> Data { get; set; } = new List<GetPeisReportByIdNoResultDataDto>();
}
public class GetPeisReportByIdNoResultDataDto
{
/// <summary>
/// 条码号
/// </summary>
public string BarcodeNo { get; set; }
/// <summary>
/// 姓名
/// </summary>
public string PatientName { get; set; }
/// <summary>
/// 身份证号码
/// </summary>
public string IdNo { get; set; }
/// <summary>
/// 手机号
/// </summary>
public string MobileTelephone { get; set; }
/// <summary>
/// 体检次数
/// </summary>
public string MedicalTimes { get; set; }
/// <summary>
/// 体检日期 格式(2024-02-20)
/// </summary>
public string MedicalDate { get; set; }
/// <summary>
/// 报告地址
/// </summary>
public string ReportUrl { get; set; }
}
}

15
Shentun.PeisReport.Api/Dto/ReportBusiness/GetPeisReportByIdNoInputDto.cs

@ -0,0 +1,15 @@
namespace Shentun.PeisReport.Api.Dto.ReportBusiness
{
public class GetPeisReportByIdNoInputDto
{
/// <summary>
/// 身份证号码
/// </summary>
public string IdNo { get; set; }
/// <summary>
/// 查询报告的数量 默认2次
/// </summary>
public int ReportCount { get; set; } = 2;
}
}

47
Shentun.PeisReport.Api/Jwt/JwtConfig.cs

@ -0,0 +1,47 @@
namespace Shentun.PeisReport.Api.Jwt
{
/// <summary>
/// Jwt配置
/// </summary>
public class JwtConfig
{
private readonly IConfigurationSection _configSection;
/// <summary>
///
/// </summary>
public JwtConfig()
{
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
var configuration = builder.Build();
_configSection = configuration.GetSection("Jwt");
}
/// <summary>
///
/// </summary>
/// <param name="configuration"></param>
public JwtConfig(IConfiguration configuration)
{
_configSection = configuration.GetSection("Jwt");
}
/// <summary>
/// 颁发者
/// </summary>
public string Issuer => _configSection.GetValue("Issuer", "Shentun");
/// <summary>
/// 颁发对象
/// </summary>
public string Audience => _configSection.GetValue("Audience", "Client");
/// <summary>
/// 安全密钥
/// </summary>
public string SecurityKey => _configSection.GetValue("SecurityKey", "Shentun8Shentun8Shentun8Shentun8");
/// <summary>
/// Web端过期时间
/// </summary>
public double WebExpiration => _configSection.GetValue<double>("WebExpiration", 100);
}
}

85
Shentun.PeisReport.Api/Jwt/JwtHelper.cs

@ -0,0 +1,85 @@
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace Shentun.PeisReport.Api.Jwt
{
/// <summary>
///
/// </summary>
public class JwtHelper
{
/// <summary>
///
/// </summary>
public JwtHelper()
{
}
/// <summary>
/// 获取JWT令牌
/// </summary>
/// <param name="claims"></param>
/// <returns></returns>
public string GetJwt(IEnumerable<Claim> claims)
{
var dateTime = DateTime.UtcNow;//世界时间
//秘钥
var jwtConfig = new JwtConfig();
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.SecurityKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
// 过期时间
double expMin= jwtConfig.WebExpiration;
DateTime expTime = dateTime.AddMinutes(expMin);
var jwt = new JwtSecurityToken(
issuer: jwtConfig.Issuer,//颁发者
audience: jwtConfig.Audience,//颁发给
claims: claims, //声明集合
notBefore: dateTime,//生效时间,这里必须使用世界时间
expires: expTime,//过期时间,这里必须使用世界时间
signingCredentials: creds);
var jwtHandler = new JwtSecurityTokenHandler().WriteToken(jwt);
return jwtHandler;
}
/// <summary>
/// 获取TokenValidationParameters
/// </summary>
/// <returns></returns>
public TokenValidationParameters GetTokenValidationParameters()
{
var jwtConfig = new JwtConfig();
TokenValidationParameters tokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = jwtConfig.Issuer,//颁发者
ValidAudience = jwtConfig.Audience,//颁发给
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.SecurityKey)),
/***********************************TokenValidationParameters的参数默认值***********************************/
RequireSignedTokens = true,
// SaveSigninToken = false,
// ValidateActor = false,
// 将下面两个参数设置为false,可以不验证Issuer和Audience,但是不建议这样做。
ValidateAudience = true,//颁发给验证
ValidateIssuer = true,//颁发者验证
ValidateIssuerSigningKey = true,
// 是否要求Token的Claims中必须包含 Expires
RequireExpirationTime = true,
// 允许的服务器时间偏移量
ClockSkew = TimeSpan.FromSeconds(300),
// 是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比
ValidateLifetime = true
};
return tokenValidationParameters;
}
}
}

61
Shentun.PeisReport.Api/Program.cs

@ -1,6 +1,12 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using NLog.Web;
using Shentun.PeisReport.Api.Jwt;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
@ -23,6 +29,28 @@ builder.Services.AddSwaggerGen(opt =>
});
var apiGroupNames = configuration["ApiGroupName"];
builder.Services.AddSwaggerGen(c =>
{
if (apiGroupNames.Contains("JianLiApi"))
{
c.SwaggerDoc("JianLiApi", new OpenApiInfo { Title = "监利医院", Version = "V1", Description = "监利医院" });
}
if (apiGroupNames.Contains("QingHaiWuYuanApi"))
{
c.SwaggerDoc("QingHaiWuYuanApi", new OpenApiInfo { Title = "青海五院", Version = "V1", Description = "青海五院" });
}
var baseDirectory = AppContext.BaseDirectory;
//中文注释
var commentsFile = Path.Combine(baseDirectory, "Shentun.PeisReport.Api.xml");
c.IncludeXmlComments(commentsFile, true);
});
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll",
@ -32,6 +60,22 @@ builder.Services.AddCors(options =>
.AllowAnyHeader());
});
var jwtHelper = new JwtHelper();
//添加JWT 认证服务
builder.Services.AddAuthentication(opt =>
{
opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(opt =>
{
opt.TokenValidationParameters = jwtHelper.GetTokenValidationParameters();
});
var app = builder.Build();
@ -40,7 +84,15 @@ var isSwagger = Convert.ToBoolean(configuration["Swagger:IsEnabled"]);
if (isSwagger)
{
app.UseSwagger();
app.UseSwaggerUI();
//app.UseSwaggerUI();
app.UseSwaggerUI(c =>
{
if (apiGroupNames.Contains("JianLiApi"))
c.SwaggerEndpoint($"/swagger/JianLiApi/swagger.json", "监利医院Api"); //分组显示
if (apiGroupNames.Contains("QingHaiWuYuanApi"))
c.SwaggerEndpoint($"/swagger/QingHaiWuYuanApi/swagger.json", "青海五院Api"); //分组显示
//c.DefaultModelExpandDepth(-1);
});
}
@ -51,10 +103,17 @@ app.UseStaticFiles(new StaticFileOptions
FileProvider = new PhysicalFileProvider(configuration["ReportVirtualPath:RealPath"]),
RequestPath = configuration["ReportVirtualPath:RequestPath"]
});
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(configuration["LisReportVirtualPath:RealPath"]),
RequestPath = configuration["LisReportVirtualPath:RequestPath"]
});
app.UseCors("AllowAll");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

1
Shentun.PeisReport.Api/Shentun.PeisReport.Api.csproj

@ -8,6 +8,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.0" />
<PackageReference Include="NLog.Web.AspNetCore" Version="5.3.14" />
<PackageReference Include="SqlSugarCore" Version="5.1.4.169" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />

13
Shentun.PeisReport.Api/WeatherForecast.cs

@ -1,13 +0,0 @@
namespace Shentun.PeisReport.Api
{
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string? Summary { get; set; }
}
}

18
Shentun.PeisReport.Api/appsettings.json

@ -8,15 +8,27 @@
"AllowedHosts": "*",
"ConnectionStrings": {
"Default": "server=140.143.162.39;uid=sa;pwd=shentun;database=mypeis;Encrypt=false;",
"Report": "User Id=tjdj_08;Password=Tfdj_yixm7u8X;Data Source=TJDJ;Unicode=True"
"Report": "User Id=tjdj_08;Password=Tfdj_yixm7u8X;Data Source=TJDJ;Unicode=True",
"Lis": "server=140.143.162.39;uid=sa;pwd=shentun;database=mypeis;Encrypt=false;"
},
"HostAddress": "https://localhost:7005",
"ZWHostAddress": "https://localhost:7005",
"ReportVirtualPath": {
"RealPath": "E:\\peis_pdf",
"RequestPath": "/Pdf"
"RequestPath": "/PeisPdf"
},
"LisReportVirtualPath": {
"RealPath": "E:\\peis_pdf",
"RequestPath": "/LisPdf"
},
"Swagger": {
"IsEnabled": true
}
},
"Jwt": {
"Issuer": "Shentun", //
"Audience": "Client", //
"SecurityKey": "Shentun8Shentun8Shentun8Shentun8", //
"WebExpiration": 100 //web 144024
},
"ApiGroupName": "JianLiApi"
}
Loading…
Cancel
Save