一、发送企微群消息和消息早知道
public class ContentHttps
{
/// <summary>
/// 发送企业微信群组
/// </summary>
/// <param name="chatID">群ID</param>
/// <param name="text">发送的消息文本</param>
/// <returns></returns>
public async Task<string> WeChatGroup(string ChatId, string Content)
{
string encodedContent = HttpUtility.UrlEncode(Content);
string url = "http://bcgw.api.luxsan-ict.com:8000/lzwxapi/api/WorkWeChat/GroupTextMessage1";
string Code = "CN3G_zabbix1";
string Password = "Y7ftCrnmlI5N4y4G1";
int SendApp = 1;
string postData = $"Code={Code}&Password={Password}&SendApp={SendApp}&ChatId={ChatId}&Content={encodedContent}";
using HttpClient client = new HttpClient();
var contentBytes = new StringContent(postData, Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage response = await client.PostAsync(url, contentBytes);
string responseText = await response.Content.ReadAsStringAsync();
string ErrMsg = responseText.ToString();
return JsonConvert.SerializeObject(new { status = "200", msg = "操作成功", data = ErrMsg }, Formatting.Indented);
}
public class Text
{
public string? content { get; set; }
}
/// <summary>
/// 企业微信消息早知道
/// </summary>
/// <param name="EmpCodes">人员工号,多个用逗号隔开</param>
/// <param name="Content">需要发送的内容</param>
/// <returns></returns>
public async Task<string> WeChat(string empCodes, string content)
{
string encodedContent = HttpUtility.UrlEncode(content);
string url = "http://gw.api.luxsan-ict.com:8000/lzwxapi/api/WorkWeChat/SendTextMessage2";
string account = "CN3G_zabbix2";
string password = "Y7ftCrnmlI5N4y4G2";
int sendApp = 1;
string postData = $"Account={account}&Password={password}&SendApp={sendApp}&EmpCodes={empCodes}&Content={encodedContent}";
using HttpClient client = new HttpClient();
var contentBytes = new StringContent(postData, Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage response = await client.PostAsync(url, contentBytes);
string responseText = await response.Content.ReadAsStringAsync();
ApiResponse ErrMsg = JsonConvert.DeserializeObject<ApiResponse>(responseText);
return JsonConvert.SerializeObject(new { status = "200", msg = "操作成功", data = ErrMsg.ErrMsg }, Formatting.Indented);
}
public class ApiResponse
{
public bool IsSuccess { get; set; }
public string? ErrMsg { get; set; }
}
}
二、调用公司账号发送邮件
/// <summary>
/// 发邮件带抄送人
/// </summary>
/// <param name="MailContent">邮件内容</param>
/// <param name="IsBodyHtml">是否是HTML</param>
/// <param name="Theme">邮件主旨</param>
/// <param name="AttList">附件</param>
/// <param name="Receiver">接收人</param>
/// <param name="Copyer">抄送人</param>
/// <returns></returns>
public bool Send_Risk_Mail(string MailContent, bool IsBodyHtml, string Theme, List<string> AttList, List<string> Receiver, List<string> Copyer)
{
MailMessage myMail = new MailMessage
{
From = new MailAddress("iFactory@luxshare-ict.com"),
Subject = Theme,
SubjectEncoding = Encoding.UTF8,
Body = MailContent,
BodyEncoding = Encoding.UTF8,
IsBodyHtml = IsBodyHtml,
Priority = MailPriority.High
};
if (AttList.Count != 0)
{
for (int j = 0; j < AttList.Count; j++)
{
myMail.Attachments.Add(new Attachment(AttList[j].Trim()));
}
}
SmtpClient sender = new SmtpClient("10.190.30.220", 8995)
{
UseDefaultCredentials = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
EnableSsl = false
};
sender.Credentials = new NetworkCredential("iFactory", "LuxshareICT@2105#");
for (int i = 0; i < Receiver.Count; i++)//发送邮件
{
string receivers = Receiver[i].ToString().Trim();
if (IsValidEmail(receivers) && (receivers.ToUpper().Contains("LUXSAN") || receivers.ToUpper().Contains("LUXSHARE")))
{
myMail.To.Add(new MailAddress(Receiver[i].ToString().Trim()));
}
}
for (int i = 0; i < Copyer.Count; i++)//抄送邮件
{
string copyers = Copyer[i].ToString().Trim();
if (IsValidEmail(copyers) && (copyers.ToUpper().Contains("LUXSAN") || copyers.ToUpper().Contains("LUXSHARE")))
{
myMail.CC.Add(new MailAddress(Copyer[i].ToString().Trim()));
}
}
sender.Send(myMail);
//Console.WriteLine($"{myMail.Subject}");
foreach (Attachment item in myMail.Attachments)
{
item.Dispose();
}
return true;
}
示例
public string Send_Risk_Alert_Email(M_RISK_CHECK_ALERT_INFO model)
{
itms_05_dal_Cosmetic_19_Risk_Check_Dashboard.A_M_RISK_CHECK_ALERT_INFO(model);
//处理图片相关信息
DataTable NG_Photo = itms_05_dal_Cosmetic_19_Risk_Check_Dashboard.Get_File_By_File_ID(model.NG_PHOTO);
string NG_File_Path = "";
string NG_File_Name = "";
string NG_File_Picture = "";
if (NG_Photo.Rows.Count > 0)
{
NG_File_Path = NG_Photo.Rows[0]["file_path"].ToString();
NG_File_Name = NG_Photo.Rows[0]["file_name"].ToString();
NG_File_Picture = "<img src = " + NG_File_Name + " width = '400' style='max-width:100%'>";
}
DataTable Before_Photo = itms_05_dal_Cosmetic_19_Risk_Check_Dashboard.Get_File_By_File_ID(model.IMPROVE_BEFORE);
string Before_File_Path = "";
string Before_File_Name = "";
string Before_File_Picture = "";
if (Before_Photo.Rows.Count > 0)
{
Before_File_Path = Before_Photo.Rows[0]["file_path"].ToString();
Before_File_Name = Before_Photo.Rows[0]["file_name"].ToString();
Before_File_Picture = "<img src = " + Before_File_Name + " width = '400' style='max-width:100%'> ";
}
DataTable After_Photo = itms_05_dal_Cosmetic_19_Risk_Check_Dashboard.Get_File_By_File_ID(model.IMPROVE_AFTER);
string After_File_Path = "";
string After_File_Name = "";
string After_File_Picture = "";
if (After_Photo.Rows.Count > 0)
{
After_File_Path = After_Photo.Rows[0]["file_path"].ToString();
After_File_Name = After_Photo.Rows[0]["file_name"].ToString();
After_File_Picture = "<img src = " + After_File_Name + " width = '400' style='max-width:100%'> ";
}
//存入attach文件中
List<string> AttList = new List<string>();
//从FTP上把报告模板下载到项目本地路径,命名为fileName
using (var client = new SftpClient("10.42.24.116", 8022, "imas", "imas")) //创建连接对象
{
client.Connect(); //连接
if (NG_Photo.Rows.Count > 0)
{
using (FileStream file1 = File.OpenWrite(NG_File_Name))
{
client.DownloadFile(NG_File_Path + NG_File_Name, file1);
}
//AttList.Add(@"D:\git\isqs\itms_04_application_programming_interface\itms_01_api\" + NG_File_Name);
AttList.Add("/app/" + NG_File_Name);
}
if (Before_Photo.Rows.Count > 0)
{
using (FileStream file2 = File.OpenWrite(Before_File_Name))
{
client.DownloadFile(Before_File_Path + Before_File_Name, file2);
}
AttList.Add("/app/" + Before_File_Name);
}
if (After_Photo.Rows.Count > 0)
{
using (FileStream file3 = File.OpenWrite(After_File_Name))
{
client.DownloadFile(After_File_Path + After_File_Name, file3);
}
AttList.Add("/app/" + After_File_Name);
}
}
//判断部门和线体是否标色
List<string> unit_list = itms_05_dal_Cosmetic_19_Risk_Check_Dashboard.G_Risk_Email_Address(model.DUTY_UNITS).Where(o => o.Value == "1").Select(o => o.Key).ToList();
Dictionary<string, string> line_list = itms_05_dal_Cosmetic_19_Risk_Check_Dashboard.G_Risk_Email_Address(model.ACTION_LINES);
string HtmlContent = @"
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<title>Document</title>
<style type='text/css'>
/*表格样式*/
p {
margin-left: 2%;
}
table {
width: 98%;
background: rgb(255, 255, 255);
margin: 2% auto;
border-collapse: collapse;
margin-left: 2%;
table-layout: fixed; /* 强制表格布局为固定 */
}
td {
height: 25px;
line-height: 25px;
text-align: center;
border: 1px solid #ccc;
width: 12%; /* 使每个单元格占表格总宽度的12.5%,8列时 */
}
th {
background:#bdd7ee;
font-weight: normal;
border: 1px solid ;
border-collapse:collapse;
width: 12%; /* 使每个单元格占表格总宽度的12.5%,8列时 */
}
.custom-table{
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0 auto;
}
.green{
background:#5b9bd5;
}
.table-row {
display: flex;
flex-wrap: wrap; /* 自动换行 */
justify-content: space-between; /* 均匀分布图片 */
}
.table-row img {
width: 30%; /* 设置图片宽度 */
box-sizing: border-box;
}
</style>
</head>
Dear All: <p>
" + model.MODEL + "批量异常 Alert,"+ DateTime.Now.ToString() + @",请查看</p>
<p>具体信息可登入以下网址查看:<a href=""https://isqs.luxsan-ict.com/home"">点击前往</a></p>
<table class='custom-table' >
<tbody>
<tr>
<th colspan='8' class = 'left'>
批量异常信息:" + model.SOME_DATE + @"
</th>
</tr>
<tr>
<td>
线别
</td>
<td>
" + model.LINE + @"
</td>
<td>
风险站
</td>
<td>
" + model.STATION + @"
</td>
<td>
站别名称
</td>
<td colspan='3' class = 'left'>
" + model.STATION_NAME + @"
</td>
</tr>
<tr>
<td>
NG 位置
</td>
<td colspan='2'>
" + model.NG_LOCATION + @"
</td>
<td>
风险点
</td>
<td colspan='4' class = 'left'>
" + model.RISK_POINT + @"
</td>
</tr>
<tr>
<td class = 'left'>
对策
</td>
<td colspan='7' class = 'left'>
" + model.ACTION + @"
</td>
</tr>
<tr>
<th colspan='2'>
NG 图片
</th>
<th colspan='3'>
改善前
</th>
<th colspan='3'>
改善后
</th>
</tr>
<tr>
<td colspan='2'>
" + NG_File_Picture + @"
</td>
<td colspan='3'>
" + Before_File_Picture + @"
</td>
<td colspan='3'>
" + After_File_Picture + @"
</td>
</tr>
<tr>
<th>
责任单位
</th>
<td "; if (unit_list.Contains("FATP")) { HtmlContent += "class = 'green'"; }
HtmlContent += @">
FATP
</td>
<td "; if (unit_list.Contains("AE")) { HtmlContent += "class = 'green'"; }
HtmlContent += @">
AE
</td>
<td "; if (unit_list.Contains("ME")) { HtmlContent += "class = 'green'"; }
HtmlContent += @">
ME
</td>
<td "; if (unit_list.Contains("AFTE")) { HtmlContent += "class = 'green'"; }
HtmlContent += @">
AFTE
</td>
<td "; if (unit_list.Contains("AD")) { HtmlContent += "class = 'green'"; }
HtmlContent += @">
AD
</td>
<td "; if (unit_list.Contains("RF")) { HtmlContent += "class = 'green'"; }
HtmlContent += @">
RF
</td>
<td "; if (unit_list.Contains("APDA")) { HtmlContent += "class = 'green'"; }
HtmlContent += @">
APDA
</td>
</tr>
<tr>
<th colspan='8'>
同步导入Action线别:
</th>
</tr>";
int i = 0;
foreach (var item in line_list)
{
if (i % 4 == 0)
{
HtmlContent += @" <tr> ";
}
HtmlContent += @$" <td> {item.Key} </td> ";
HtmlContent += item.Value == "1" ? @$" <td class = 'green'> V </td> " : @$" <td></td> ";//判断是否加上绿色背景
if ((line_list.Count - i == 1) && ((i+1) % 4 == 0))
{
HtmlContent += @" </tr> ";
}
i++;
}
HtmlContent += @"
<tr>
<th colspan='8' class = 'left'>
备注:
</th>
</tr>
<tr>
<td colspan='8' class = 'left'>
" + model.REMARK + @"
</td>
</tr>
</tbody>
</table>
<p>本系统由系统发出,请勿直接回复</p>
<body>
</body>
</html>";
//收件人
List<string> Receiver_list = itms_05_dal_Cosmetic_19_Risk_Check_Dashboard.G_Alert_Email_Receiver(model);
//抄送人
string Copyer = model.SITE == "LXKS" ? "Kawa@luxsan-ict.com" : "Kawa@luxsan-ict.com";
List<string> Copyer_list = new List<string>() { Copyer };
string theme = $"[ISQS] {model.MODEL} IPQC批量异常Alert {DateTime.Now.ToString()}";
if (itms_05_dal_Cosmetic_19_Risk_Check_Dashboard.Send_Risk_Mail(HtmlContent, true, theme, AttList, Receiver_list, Copyer_list))
{
return JsonConvert.SerializeObject(new { status = 200, msg = "发送成功" }, Formatting.Indented);
}
else
{
return JsonConvert.SerializeObject(new { status = 200, msg = "发送失败" }, Formatting.Indented);
}
//删除图片
if (System.IO.File.Exists(NG_File_Name))
{
File.Delete(NG_File_Name);
}
if (System.IO.File.Exists(Before_File_Name))
{
File.Delete(Before_File_Name);
}
if (System.IO.File.Exists(After_File_Name))
{
File.Delete(After_File_Name);
}
return "ok";
}
三、调用公司内部OA账号密码实现登录
public class LDAPUtil
{
public static string? Host { get; private set; }
public static string? BindDN { get; private set; }
public static string? BindPassword { get; private set; }
public static int Port { get; private set; }
public static string? BaseDC { get; private set; }
public static string? CookieName { get; private set; }
public static bool Validate(string username, string password)
{
Host = "10.191.32.30";
Port = 8389;
BindDN = "CN=lzldap,OU=Service Accounts,OU=Special Accounts";
BindPassword = "Luxsan@2021#2021!";
BaseDC = "DC=luxshare,DC=com,DC=cn";
CookieName = "testcookiename";
using var conn = new LdapConnection();
conn.Connect(Host, Port);
conn.Bind($"{BindDN},{BaseDC}", BindPassword);
var entities =
conn.Search(BaseDC, LdapConnection.ScopeSub,
$"(sAMAccountName={username})",
new string[] { "sAMAccountName" }, false);
string? userDn = null;
while (entities.HasMore())
{
var entity = entities.Next();
var account = entity.GetAttribute("sAMAccountName");
//If you need to Case insensitive, please modify the below code.
if (account != null && account.StringValue.ToUpper() == username.ToUpper())
{
userDn = entity.Dn;
break;
}
}
if (string.IsNullOrWhiteSpace(userDn)) return false;
conn.Bind(userDn, password);
conn.Disconnect();
return true;
}
}
四、文件相关
1、上传文件
/// <summary>
/// 上传文件
/// </summary>
/// <param name="file">上传的文件</param>
/// <param name="uploadName">上传人</param>
/// <param name="fileClass">文件夹类别:例如 IQC,QOC,UPH</param>
/// <returns></returns>
public string PostFile(IFormFile file, string uploadName, string fileClass)
{
string GUID = "";
if (file != null)
{
string FileName = file.FileName; //获取上传的文件名
long FileSize = file.Length; //得到上传文件大小,单位 bytes
//定义文件路径 IMAS
string fileDate = DateTime.Now.ToString("yyyy/MM").Replace("/", string.Empty); //以月份命名文件夹
string F_fileDir = "/ISQS/" + fileClass + "/"; //父级目录 例如文件夹目录:/IMAS_X2/IQC/
string fileDir = "/ISQS/" + fileClass + "/" + fileDate + "/"; //当前目录 例如文件夹目录:/IMAS_X2/IQC/202112/
//定义文件名
string uploadTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");//上传时间
string fileFlag = uploadTime.Replace("/", string.Empty).Replace("-", string.Empty).Replace(":", string.Empty).Replace(" ", "-") + "-";
string newFileName = fileFlag + FileName; //文件名拼接上传时间确保文件名不重复 2021/12/12 23:09:09 文件名:20211212-230909-Lang.docx
//创建连接对象,ftpAddress是ip地址如: 47.100.11.12 第二个参数是端口号,第三四个是用户名密码
using (var client = new SftpClient("10.42.24.116", 8022, "imas", "imas"))
{
client.Connect(); //连接
//如果文件夹不存在,则新建文件夹
if (!client.Exists(F_fileDir))
{
client.CreateDirectory(F_fileDir);
}
if (!client.Exists(fileDir))
{
client.CreateDirectory(fileDir);
}
MemoryStream fs = new MemoryStream();
file.CopyTo(fs);//把file赋给fs
client.BufferSize = 20 * 1024 * 1024;
fs.Seek(0, SeekOrigin.Begin);
client.UploadFile(fs, fileDir + newFileName);
fs.Dispose();
}
GUID = Guid.NewGuid().ToString();
//相关信息记录插到数据库
P_FILE_INFO p_File_Info = new()
{
FILE_ID = GUID,
FILE_PATH = fileDir,
FILE_NAME = newFileName,
C_EMP_NO = uploadName,
FILE_SIZE = Convert.ToInt32(FileSize)
};
DBHSqlSugar<P_FILE_INFO> dbh = new();
dbh.Insert("3", p_File_Info);
}
return GUID;
}
2、下载文件
/// <summary>
/// 下载文件
/// </summary>
/// <param name="fileID">文件ID</param>
/// <param name="DownLoadUser">下载人</param>
/// <param name="buffer">返回二进制文件信息</param>
/// <param name="fileName">返回文件地址</param>
/// <returns></returns>
public byte[] DownloadFile(string fileID, string DownLoadUser, out byte[] buffer, out string fileName)
{
buffer = new byte[0];
fileName = "";
DataTable Dt = Get_Link_File_ID(fileID);
if (Dt.Rows.Count > 0)
{
string filePath = Dt.Rows[0]["FILE_PATH"].ToString();
fileName = Dt.Rows[0]["FILE_NAME"].ToString();
Dt.Rows[0]["FILE_PATH"].ToString();
if (filePath != null)
{
using (var client = new SftpClient("10.42.24.116", 8022, "imas", "imas")) //创建连接对象
{
client.Connect(); //连接
buffer = client.ReadAllBytes("/" + filePath);
}
}
P_DOWNLOAD_FILE_LOG p_Downolad_File_Log = new()
{
FILE_GUID = fileID,
FILE_NAME = fileName,
C_EMP_NO = DownLoadUser
};
int nums = Db.GetConnection("3").Insertable(p_Downolad_File_Log).ExecuteCommand();
}
return buffer;
}
//BLL 层调用
public (byte[], string) Get_Files(string file_id, string emp_no)
{
Common_01_System_UploadFile.DownloadFile(file_id, emp_no, out byte[] buffer, out string fileName);
return (buffer, fileName);
}
//API层调用
/// <summary>
/// 文件 下载
/// </summary>
/// <param name="file_id"></param>
/// <param name="emp_no"></param>
/// <returns></returns>
[HttpGet("Get_Files", Name = "Get_Files")]
public FileContentResult Get_Files(string file_id, string emp_no)
{
(byte[] buffer, string fileName) = Itms_01_Bll_Common_01_System.Get_Files(file_id, emp_no);
return File(buffer, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); //关键语句
}
3、删除文件
/// <summary>
/// 删除文件
/// </summary>
/// <param name="fileID"></param>
/// <returns></returns>
public int DeleteFile(string fileID)
{
int nums = 0;
DataTable Dt = Get_Link_File_ID(fileID);//获取文件信息
if (Dt.Rows.Count > 0)
{
string fileDir = Dt.Rows[0]["FILE_PATH"].ToString();
if (string.IsNullOrEmpty(fileDir))
return 0;
using (var client = new SftpClient("10.42.24.116", 8022, "imas", "imas"))
{
client.Connect(); //连接
if (client.Exists(fileDir))
{
client.DeleteFile(fileDir);//删除FTP上的文件
nums = Db.GetConnection("3").Deleteable<P_FILE_INFO>().Where(it => it.FILE_ID == fileID).ExecuteCommand();
}
}
}
return nums;
}
五、记录Log
public class ApiLogFilter : IAsyncActionFilter
{
private readonly ILogger logger;
public ApiLogFilter(ILogger<ApiLogFilter> logger)
{
this.logger = logger;
}
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
S_LOG_INFO s_Log_Info = new S_LOG_INFO();
//请求人
foreach (var item in context.HttpContext.Request.Headers)
{
if (item.Key.Equals("Operator"))
s_Log_Info.C_EMP_NO = item.Value.ToString();
if (item.Key.Equals("X-Real-IP"))
s_Log_Info.CLIENT_IP = item.Value.ToString();
if (item.Key.Equals("Menu_id"))
s_Log_Info.MENU_ID = item.Value.ToString();
}
//请求参数
s_Log_Info.PARA = context.ActionArguments.ToJson();
var resultContext = await next();
//每个API请求的动作
try
{
s_Log_Info.REQUEST_HOST = resultContext.HttpContext.Request.Host.ToString();
s_Log_Info.REQUEST_PATH = resultContext.HttpContext.Request.Path;
s_Log_Info.REQUEST_METHOD = resultContext.HttpContext.Request.Method;
}
catch (System.Exception)
{
s_Log_Info.ERROR = resultContext.Exception.Message.ToString();
s_Log_Info.ERROR_MSG = resultContext.Exception.StackTrace.ToString();
}
finally
{
//写入log表
List<S_LOG_INFO> list = new()
{
s_Log_Info
};
itms_01_Bll_Common_01_System.M_s_log_info(list);
}
}
}
六、异常处理中间件
public class ExceptionMiddleware
{
private readonly ILogger logger;
private readonly RequestDelegate next;
/// <summary>
/// </summary>
/// <param name="next"></param>
/// <param name="logger"></param>
public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger)
{
this.logger = logger;
this.next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await next(context);
}
catch (Exception e)
{
await ExceptionHandlerAsync(context, e);
}
}
private async Task ExceptionHandlerAsync(HttpContext context, Exception e)
{
context.Response.ContentType = "application/json";
logger.LogError(e, context.Request.Path);
var result = new Response<string>()
{
Status = 400,
msg = e.Message
};
await context.Response.WriteAsync(result.ToJson());
}
}
/// <summary>
/// </summary>
/// <typeparam name="T"></typeparam>
public class Response<T>
{
/// <summary>
/// </summary>
public int Status { get; set; } = 200;
/// <summary>
/// </summary>
public string msg { get; set; } = "操作成功!";
/// <summary>
/// </summary>
public T Data { get; set; }
/// <summary>
/// </summary>
/// <param name="data"></param>
/// <param name="msg"></param>
public void Success(T data, string msg = "")
{
this.Status = 200;
this.msg = msg;
this.Data = data;
}
}
/// <summary> 扩展方法,格式化时间
/// </summary>
public static class ObjectExtensions
{
/// <summary>
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string ToJson(this object obj)
{
var serializerSettings = new JsonSerializerSettings
{
DateFormatString = "yyyy-MM-dd HH:mm:ss",
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
return JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.None, serializerSettings);
}
}
七、program.cs
using itms_00_tools_03_common;
using itms_01_api.Middlewares;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
//builder.Services.AddControllers();
builder.Services.AddControllers(
options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true
).AddJsonOptions(options =>
{
//时间格式化响应
options.JsonSerializerOptions.Converters.Add(new JsonOptionsExt());
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.Configure<KestrelServerOptions>(options =>
{
options.Limits.MaxRequestBodySize = 130000000;
});
//跨域
builder.Services.AddCors(
options =>
{
options.AddPolicy("CorsPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
builder.Services.AddMvc(options =>
{
options.Filters.Add(typeof(ApiLogFilter));
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(
options =>
{
//添加安全定义
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "请输入token,格式为 Bearer xxxxxxxx(注意中间必须有空格)",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
BearerFormat = "JWT",
Scheme = "Bearer"
});
//添加安全要求
options.AddSecurityRequirement(new OpenApiSecurityRequirement {
{
new OpenApiSecurityScheme{
Reference =new OpenApiReference{
Type = ReferenceType.SecurityScheme,
Id ="Bearer"
}
},new string[]{ }
}
});
/*
//只有参数里的V1是要和下面配置路径保持一致,
//剩下的乱写也不报错 但是不推荐
options.SwaggerDoc("V1", new OpenApiInfo
{
Title = $"项目名",
Version = "V1",
Description = $"项目名:V1版本"
});
*/
//生成多个文档显示
typeof(ApiVersions).GetEnumNames().ToList().ForEach(version =>
{
//添加文档介绍
options.SwaggerDoc(version, new OpenApiInfo
{
Title = $"ISQS",
Version = version,
Description = $"项目名:{version}"
});
});
var file = Path.Combine(AppContext.BaseDirectory, "itms_01_api.xml"); // xml文档绝对路径
var path = Path.Combine(AppContext.BaseDirectory, file); // xml文档绝对路径
options.IncludeXmlComments(path, true); // true : 显示控制器层注释
//options.OrderActionsBy(o => o.RelativePath); // 对action的名称进行排序,如果有多个,就可以看见效果了。
var modelsfile = Path.Combine(AppContext.BaseDirectory, "itms_01_api.xml"); // xml文档绝对路径
var modelspath = Path.Combine(AppContext.BaseDirectory, modelsfile); // xml文档绝对路径
options.IncludeXmlComments(modelspath, true); // true : 显示models层注释
});
//添加后台定时任务服务
builder.Services.AddHostedService<HostingServices>();
builder.Services.AddSingleton<ClearDataForP_TERMINAL_HT>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
}
app.UseSwagger();
//跨域
app.UseCors("CorsPolicy");
app.UseMiddleware<ExceptionMiddleware>();
app.UseSwaggerUI(
options =>
{
/*
options.SwaggerEndpoint($"/swagger/V1/swagger.json",$"版本选择:V1");
*/
//如果只有一个版本也要和上方保持一致
typeof(ApiVersions).GetEnumNames().ToList().ForEach(version =>
{
//切换版本操作
//参数一是使用的哪个json文件,参数二就是个名字
options.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"{version}");
});
}
);
//app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();