Skip to content

Commit fb62932

Browse files
committed
⚡优化功能
1 parent e810afa commit fb62932

File tree

7 files changed

+273
-31
lines changed

7 files changed

+273
-31
lines changed

Infrastructure/Controllers/BaseController.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
using System;
99
using System.Collections.Generic;
1010
using System.IO;
11-
using System.Threading.Tasks;
1211
using System.Web;
1312

1413
namespace Infrastructure.Controllers
Lines changed: 252 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,252 @@
1+
using Infrastructure.Extensions;
2+
using Infrastructure.Model;
3+
using Microsoft.AspNetCore.Hosting;
4+
using Microsoft.AspNetCore.Mvc;
5+
using MiniExcelLibs;
6+
using System;
7+
using System.Collections.Generic;
8+
using System.IO;
9+
using System.Text.Encodings.Web;
10+
using System.Text.Unicode;
11+
using System.Web;
12+
using textJson = System.Text.Json;
13+
14+
namespace Infrastructure.Controllers
15+
{
16+
/// <summary>
17+
/// System.Text.Json 序列化保留
18+
/// </summary>
19+
//[ApiController]
20+
public class JsonApiController : ControllerBase
21+
{
22+
public static string TIME_FORMAT_FULL = "yyyy-MM-dd HH:mm:ss";
23+
24+
/// <summary>
25+
/// 返回成功封装
26+
/// </summary>
27+
/// <param name="data"></param>
28+
/// <param name="timeFormatStr"></param>
29+
/// <returns></returns>
30+
protected IActionResult SUCCESS(object data, string timeFormatStr = "yyyy-MM-dd HH:mm:ss")
31+
{
32+
//string jsonStr = GetJsonStr(GetApiResult(data != null ? ResultCode.SUCCESS : ResultCode.NO_DATA, data), timeFormatStr);
33+
//return Content(jsonStr, "application/json");
34+
return Ok(GetApiResult(data != null ? ResultCode.SUCCESS : ResultCode.NO_DATA, data));
35+
}
36+
37+
/// <summary>
38+
/// json输出带时间格式的
39+
/// </summary>
40+
/// <param name="apiResult"></param>
41+
/// <returns></returns>
42+
protected IActionResult ToResponse(ApiResult apiResult)
43+
{
44+
//string jsonStr = GetJsonStr(apiResult, TIME_FORMAT_FULL);
45+
46+
//return Content(jsonStr, "application/json");
47+
return Ok(apiResult);
48+
}
49+
50+
protected IActionResult ToResponse(long rows, string timeFormatStr = "yyyy-MM-dd HH:mm:ss")
51+
{
52+
string jsonStr = GetJsonStr(ToJson(rows), timeFormatStr);
53+
54+
//return Content(jsonStr, "application/json");
55+
return Ok(ToJson(rows));
56+
}
57+
58+
protected IActionResult ToResponse(ResultCode resultCode, string msg = "")
59+
{
60+
return ToResponse(new ApiResult((int)resultCode, msg));
61+
}
62+
63+
/// <summary>
64+
/// 导出Excel
65+
/// </summary>
66+
/// <param name="path">完整文件路径</param>
67+
/// <param name="fileName">带扩展文件名</param>
68+
/// <returns></returns>
69+
protected IActionResult ExportExcel(string path, string fileName)
70+
{
71+
//var webHostEnvironment = App.WebHostEnvironment;
72+
if (!Path.Exists(path))
73+
{
74+
throw new CustomException(fileName + "文件不存在");
75+
}
76+
var stream = System.IO.File.OpenRead(path); //创建文件流
77+
78+
Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
79+
return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", HttpUtility.UrlEncode(fileName));
80+
}
81+
82+
/// <summary>
83+
/// 下载文件
84+
/// </summary>
85+
/// <param name="path"></param>
86+
/// <param name="fileName">文件名,一定要带扩展名</param>
87+
/// <returns></returns>
88+
protected IActionResult DownFile(string path, string fileName)
89+
{
90+
if (!System.IO.File.Exists(path))
91+
{
92+
return NotFound();
93+
}
94+
var stream = System.IO.File.OpenRead(path); //创建文件流
95+
Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
96+
return File(stream, "application/octet-stream", HttpUtility.UrlEncode(fileName));
97+
}
98+
99+
#region 方法
100+
101+
/// <summary>
102+
/// 响应返回结果
103+
/// </summary>
104+
/// <param name="rows">受影响行数</param>
105+
/// <param name="data"></param>
106+
/// <returns></returns>
107+
protected ApiResult ToJson(long rows, object? data = null)
108+
{
109+
return rows > 0 ? ApiResult.Success("success", data) : GetApiResult(ResultCode.FAIL);
110+
}
111+
112+
/// <summary>
113+
/// 全局Code使用
114+
/// </summary>
115+
/// <param name="resultCode"></param>
116+
/// <param name="data"></param>
117+
/// <returns></returns>
118+
protected ApiResult GetApiResult(ResultCode resultCode, object? data = null)
119+
{
120+
var msg = resultCode.GetDescription();
121+
122+
return new ApiResult((int)resultCode, msg, data);
123+
}
124+
protected ApiResult Success()
125+
{
126+
return GetApiResult(ResultCode.SUCCESS);
127+
}
128+
129+
/// <summary>
130+
///
131+
/// </summary>
132+
/// <param name="apiResult"></param>
133+
/// <param name="timeFormatStr"></param>
134+
/// <returns></returns>
135+
private static string GetJsonStr(ApiResult apiResult, string timeFormatStr)
136+
{
137+
if (string.IsNullOrEmpty(timeFormatStr))
138+
{
139+
timeFormatStr = TIME_FORMAT_FULL;
140+
}
141+
//var serializerSettings = new JsonSerializerSettings
142+
//{
143+
// // 设置为驼峰命名
144+
// ContractResolver = new CamelCasePropertyNamesContractResolver(),
145+
// DateFormatString = timeFormatStr
146+
//};
147+
//return JsonConvert.SerializeObject(apiResult, Formatting.Indented, serializerSettings);
148+
var options = new textJson.JsonSerializerOptions
149+
{
150+
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),
151+
PropertyNamingPolicy = textJson.JsonNamingPolicy.CamelCase,// 设置为驼峰命名
152+
//DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault,
153+
WriteIndented = true,
154+
//Converters = { new LongToStringConverter() }
155+
};
156+
157+
//options.Converters.Add(new ValueToStringConverter());
158+
string responseResult = textJson.JsonSerializer.Serialize(apiResult, options);
159+
return responseResult;
160+
}
161+
#endregion
162+
163+
/// <summary>
164+
/// 导出Excel
165+
/// </summary>
166+
/// <typeparam name="T"></typeparam>
167+
/// <param name="list"></param>
168+
/// <param name="sheetName"></param>
169+
/// <param name="fileName"></param>
170+
protected string ExportExcel<T>(List<T> list, string sheetName, string fileName)
171+
{
172+
return ExportExcelMini(list, sheetName, fileName).Item1;
173+
}
174+
175+
/// <summary>
176+
///
177+
/// </summary>
178+
/// <typeparam name="T"></typeparam>
179+
/// <param name="list"></param>
180+
/// <param name="sheetName"></param>
181+
/// <param name="fileName"></param>
182+
/// <returns></returns>
183+
protected (string, string) ExportExcelMini<T>(List<T> list, string sheetName, string fileName)
184+
{
185+
IWebHostEnvironment webHostEnvironment = (IWebHostEnvironment)App.ServiceProvider.GetService(typeof(IWebHostEnvironment));
186+
string sFileName = $"{fileName}{DateTime.Now:MM-dd-HHmmss}.xlsx";
187+
string fullPath = Path.Combine(webHostEnvironment.WebRootPath, "export", sFileName);
188+
189+
Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
190+
191+
MiniExcel.SaveAs(fullPath, list, sheetName: sheetName);
192+
return (sFileName, fullPath);
193+
}
194+
195+
/// <summary>
196+
/// 导出多个工作表(Sheet)
197+
/// </summary>
198+
/// <param name="sheets"></param>
199+
/// <param name="fileName"></param>
200+
/// <returns></returns>
201+
protected (string, string) ExportExcelMini(Dictionary<string, object> sheets, string fileName)
202+
{
203+
IWebHostEnvironment webHostEnvironment = (IWebHostEnvironment)App.ServiceProvider.GetService(typeof(IWebHostEnvironment));
204+
string sFileName = $"{fileName}{DateTime.Now:MM-dd-HHmmss}.xlsx";
205+
string fullPath = Path.Combine(webHostEnvironment.WebRootPath, "export", sFileName);
206+
207+
Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
208+
209+
MiniExcel.SaveAs(fullPath, sheets);
210+
return (sFileName, fullPath);
211+
}
212+
213+
/// <summary>
214+
/// 下载导入模板
215+
/// </summary>
216+
/// <typeparam name="T">数据类型</typeparam>
217+
/// <param name="list">空数据类型集合</param>
218+
/// <param name="fileName">下载文件名</param>
219+
/// <returns></returns>
220+
protected (string, string) DownloadImportTemplate<T>(List<T> list, string fileName)
221+
{
222+
IWebHostEnvironment webHostEnvironment = App.WebHostEnvironment;
223+
string sFileName = $"{fileName}.xlsx";
224+
string fullPath = Path.Combine(webHostEnvironment.WebRootPath, "ImportTemplate", sFileName);
225+
226+
//不存在模板创建模板
227+
if (!Directory.Exists(fullPath))
228+
{
229+
Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
230+
}
231+
if (!Path.Exists(fullPath))
232+
{
233+
MiniExcel.SaveAs(fullPath, list, overwriteFile: true);
234+
}
235+
return (sFileName, fullPath);
236+
}
237+
238+
/// <summary>
239+
/// 下载指定文件模板
240+
/// </summary>
241+
/// <param name="fileName">下载文件名</param>
242+
/// <returns></returns>
243+
protected (string, string) DownloadImportTemplate(string fileName)
244+
{
245+
IWebHostEnvironment webHostEnvironment = (IWebHostEnvironment)App.ServiceProvider.GetService(typeof(IWebHostEnvironment));
246+
string sFileName = $"{fileName}.xlsx";
247+
string fullPath = Path.Combine(webHostEnvironment.WebRootPath, "ImportTemplate", sFileName);
248+
249+
return (sFileName, fullPath);
250+
}
251+
}
252+
}

ZR.Common/DynamicApiSimple/ApiConvention.cs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
1-
using System;
1+
using Infrastructure.Helper;
2+
using Microsoft.AspNetCore.Mvc.ActionConstraints;
3+
using Microsoft.AspNetCore.Mvc.ApplicationModels;
4+
using System;
25
using System.Collections.Generic;
36
using System.Linq;
47
using System.Text;
5-
using Infrastructure.Helper;
6-
using JinianNet.JNTemplate.Nodes;
7-
using Microsoft.AspNetCore.Mvc.ActionConstraints;
8-
using Microsoft.AspNetCore.Mvc.ApplicationModels;
98

109
namespace ZR.Common.DynamicApiSimple;
1110

ZR.Common/DynamicApiSimple/Extens/DynamicApiExtens.cs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using Microsoft.AspNetCore.Mvc.ApplicationParts;
44
using Microsoft.Extensions.DependencyInjection;
55
using Newtonsoft.Json.Converters;
6+
using Newtonsoft.Json.Serialization;
67
using System.Linq;
78
using System.Reflection;
89

@@ -35,8 +36,10 @@ public static IServiceCollection AddDynamicApi(this IServiceCollection services)
3536
options.SerializerSettings.DateFormatString = TIME_FORMAT_FULL;
3637
options.SerializerSettings.Converters.Add(new IsoDateTimeConverter
3738
{
38-
DateTimeFormat = TIME_FORMAT_FULL
39+
DateTimeFormat = TIME_FORMAT_FULL,
3940
});
41+
// 设置为驼峰命名
42+
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
4043
});
4144

4245
services.Configure<MvcOptions>(o =>

ZR.Common/DynamicApiSimple/JsonModelBinderProvider.cs

Lines changed: 0 additions & 24 deletions
This file was deleted.

ZR.Service/HelloService.cs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using Infrastructure;
22
using Infrastructure.Attribute;
33
using Infrastructure.Model;
4+
using Microsoft.AspNetCore.Authorization;
45
using Microsoft.AspNetCore.Mvc;
56
using SqlSugar.IOC;
67
using ZR.Admin.WebApi.Filters;
@@ -77,5 +78,16 @@ public ApiResult SayHello3()
7778
{
7879
throw new CustomException("自定义异常");
7980
}
81+
82+
/// <summary>
83+
/// 返回json内容
84+
/// </summary>
85+
/// <param name="userDto"></param>
86+
/// <returns></returns>
87+
[AllowAnonymous]
88+
public ApiResult SayHelloJson([FromBody] SysUserDto userDto)
89+
{
90+
return new ApiResult(100, "success", userDto);
91+
}
8092
}
8193
}

ZR.Service/IService/IHelloService.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,5 +18,6 @@ public interface IHelloService : IBaseService<ArticleCategory>
1818
string SayHello(string name);
1919
ApiResult SayHello2([FromBody] SysUserDto userDto);
2020
ApiResult SayHello3();
21+
ApiResult SayHelloJson([FromBody] SysUserDto userDto);
2122
}
2223
}

0 commit comments

Comments
 (0)