using Infrastructure.Extensions; using Infrastructure.Model; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using MiniExcelLibs; using System; using System.Collections.Generic; using System.IO; using System.Text.Encodings.Web; using System.Text.Unicode; using System.Web; using textJson = System.Text.Json; namespace Infrastructure.Controllers { /// /// System.Text.Json 序列化保留 /// //[ApiController] public class JsonApiController : ControllerBase { public static string TIME_FORMAT_FULL = "yyyy-MM-dd HH:mm:ss"; /// /// 返回成功封装 /// /// /// /// protected IActionResult SUCCESS(object data, string timeFormatStr = "yyyy-MM-dd HH:mm:ss") { //string jsonStr = GetJsonStr(GetApiResult(data != null ? ResultCode.SUCCESS : ResultCode.NO_DATA, data), timeFormatStr); //return Content(jsonStr, "application/json"); return Ok(GetApiResult(data != null ? ResultCode.SUCCESS : ResultCode.NO_DATA, data)); } /// /// json输出带时间格式的 /// /// /// protected IActionResult ToResponse(ApiResult apiResult) { //string jsonStr = GetJsonStr(apiResult, TIME_FORMAT_FULL); //return Content(jsonStr, "application/json"); return Ok(apiResult); } protected IActionResult ToResponse(long rows, string timeFormatStr = "yyyy-MM-dd HH:mm:ss") { string jsonStr = GetJsonStr(ToJson(rows), timeFormatStr); //return Content(jsonStr, "application/json"); return Ok(ToJson(rows)); } protected IActionResult ToResponse(ResultCode resultCode, string msg = "") { return ToResponse(new ApiResult((int)resultCode, msg)); } /// /// 导出Excel /// /// 完整文件路径 /// 带扩展文件名 /// protected IActionResult ExportExcel(string path, string fileName) { //var webHostEnvironment = App.WebHostEnvironment; if (!Path.Exists(path)) { throw new CustomException(fileName + "文件不存在"); } var stream = System.IO.File.OpenRead(path); //创建文件流 Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition"); return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", HttpUtility.UrlEncode(fileName)); } /// /// 下载文件 /// /// /// 文件名,一定要带扩展名 /// protected IActionResult DownFile(string path, string fileName) { if (!System.IO.File.Exists(path)) { return NotFound(); } var stream = System.IO.File.OpenRead(path); //创建文件流 Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition"); return File(stream, "application/octet-stream", HttpUtility.UrlEncode(fileName)); } #region 方法 /// /// 响应返回结果 /// /// 受影响行数 /// /// protected ApiResult ToJson(long rows, object? data = null) { return rows > 0 ? ApiResult.Success("success", data) : GetApiResult(ResultCode.FAIL); } /// /// 全局Code使用 /// /// /// /// protected ApiResult GetApiResult(ResultCode resultCode, object? data = null) { var msg = resultCode.GetDescription(); return new ApiResult((int)resultCode, msg, data); } protected ApiResult Success() { return GetApiResult(ResultCode.SUCCESS); } /// /// /// /// /// /// private static string GetJsonStr(ApiResult apiResult, string timeFormatStr) { if (string.IsNullOrEmpty(timeFormatStr)) { timeFormatStr = TIME_FORMAT_FULL; } //var serializerSettings = new JsonSerializerSettings //{ // // 设置为驼峰命名 // ContractResolver = new CamelCasePropertyNamesContractResolver(), // DateFormatString = timeFormatStr //}; //return JsonConvert.SerializeObject(apiResult, Formatting.Indented, serializerSettings); var options = new textJson.JsonSerializerOptions { Encoder = JavaScriptEncoder.Create(UnicodeRanges.All), PropertyNamingPolicy = textJson.JsonNamingPolicy.CamelCase,// 设置为驼峰命名 //DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault, WriteIndented = true, //Converters = { new LongToStringConverter() } }; //options.Converters.Add(new ValueToStringConverter()); string responseResult = textJson.JsonSerializer.Serialize(apiResult, options); return responseResult; } #endregion /// /// 导出Excel /// /// /// /// /// protected string ExportExcel(List list, string sheetName, string fileName) { return ExportExcelMini(list, sheetName, fileName).Item1; } /// /// /// /// /// /// /// /// protected (string, string) ExportExcelMini(List list, string sheetName, string fileName) { IWebHostEnvironment webHostEnvironment = (IWebHostEnvironment)App.ServiceProvider.GetService(typeof(IWebHostEnvironment)); string sFileName = $"{fileName}{DateTime.Now:MM-dd-HHmmss}.xlsx"; string fullPath = Path.Combine(webHostEnvironment.WebRootPath, "export", sFileName); Directory.CreateDirectory(Path.GetDirectoryName(fullPath)); MiniExcel.SaveAs(fullPath, list, sheetName: sheetName); return (sFileName, fullPath); } /// /// 导出多个工作表(Sheet) /// /// /// /// protected (string, string) ExportExcelMini(Dictionary sheets, string fileName) { IWebHostEnvironment webHostEnvironment = (IWebHostEnvironment)App.ServiceProvider.GetService(typeof(IWebHostEnvironment)); string sFileName = $"{fileName}{DateTime.Now:MM-dd-HHmmss}.xlsx"; string fullPath = Path.Combine(webHostEnvironment.WebRootPath, "export", sFileName); Directory.CreateDirectory(Path.GetDirectoryName(fullPath)); MiniExcel.SaveAs(fullPath, sheets); return (sFileName, fullPath); } /// /// 下载导入模板 /// /// 数据类型 /// 空数据类型集合 /// 下载文件名 /// protected (string, string) DownloadImportTemplate(List list, string fileName) { IWebHostEnvironment webHostEnvironment = App.WebHostEnvironment; string sFileName = $"{fileName}.xlsx"; string fullPath = Path.Combine(webHostEnvironment.WebRootPath, "ImportTemplate", sFileName); //不存在模板创建模板 if (!Directory.Exists(fullPath)) { Directory.CreateDirectory(Path.GetDirectoryName(fullPath)); } if (!Path.Exists(fullPath)) { MiniExcel.SaveAs(fullPath, list, overwriteFile: true); } return (sFileName, fullPath); } /// /// 下载指定文件模板 /// /// 下载文件名 /// protected (string, string) DownloadImportTemplate(string fileName) { IWebHostEnvironment webHostEnvironment = (IWebHostEnvironment)App.ServiceProvider.GetService(typeof(IWebHostEnvironment)); string sFileName = $"{fileName}.xlsx"; string fullPath = Path.Combine(webHostEnvironment.WebRootPath, "ImportTemplate", sFileName); return (sFileName, fullPath); } } }