代码生成优化&配置文件优化

This commit is contained in:
不做码农 2023-12-09 14:37:20 +08:00
parent dc6f41d96e
commit 5375b9e308
9 changed files with 136 additions and 57 deletions

View File

@ -15,6 +15,7 @@ namespace Infrastructure.Controllers
/// <summary> /// <summary>
/// web层通用数据处理 /// web层通用数据处理
/// </summary> /// </summary>
//[ApiController]
public class BaseController : ControllerBase public class BaseController : ControllerBase
{ {
public static string TIME_FORMAT_FULL = "yyyy-MM-dd HH:mm:ss"; public static string TIME_FORMAT_FULL = "yyyy-MM-dd HH:mm:ss";

View File

@ -0,0 +1,51 @@
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace ZR.Infrastructure.ModelBinder
{
public class CommaSeparatedArrayModelBinder<T> : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (valueProviderResult == ValueProviderResult.None)
{
return Task.CompletedTask;
}
var value = valueProviderResult.FirstValue;
if (string.IsNullOrEmpty(value))
{
return Task.CompletedTask;
}
try
{
var array = value.Split(',').Select(x => (T)Convert.ChangeType(x, typeof(T))).ToArray();
bindingContext.Result = ModelBindingResult.Success(array);
}
catch
{
bindingContext.ModelState.TryAddModelError(bindingContext.ModelName, "Invalid value format");
}
return Task.CompletedTask;
}
}
public class CommaSeparatedArrayModelBinderProvider<T> : IModelBinderProvider
{
public IModelBinder? GetBinder(ModelBinderProviderContext context)
{
if (context.Metadata.ModelType == typeof(T[]))
{
return new BinderTypeModelBinder(typeof(CommaSeparatedArrayModelBinder<T>));
}
return null;
}
}
}

View File

@ -9,3 +9,4 @@ global using Infrastructure.Extensions;
global using Infrastructure.Controllers; global using Infrastructure.Controllers;
global using ZR.ServiceCore.Middleware; global using ZR.ServiceCore.Middleware;
global using ZR.ServiceCore.Services; global using ZR.ServiceCore.Services;
global using ZR.Infrastructure.ModelBinder;

View File

@ -16,7 +16,12 @@ var builder = WebApplication.CreateBuilder(args);
builder.Host.UseNLog(); builder.Host.UseNLog();
// Add services to the container. // Add services to the container.
builder.Services.AddControllers(); builder.Services.AddControllers(options =>
{
options.ModelBinderProviders.Insert(0, new CommaSeparatedArrayModelBinderProvider<string>());
options.ModelBinderProviders.Insert(0, new CommaSeparatedArrayModelBinderProvider<int>());
options.ModelBinderProviders.Insert(0, new CommaSeparatedArrayModelBinderProvider<long>());
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer(); builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(); builder.Services.AddSwaggerGen();
@ -37,7 +42,8 @@ builder.Services.AddIPRate(builder.Configuration);
builder.Services.AddHttpContextAccessor(); builder.Services.AddHttpContextAccessor();
//绑定整个对象到Model上 //绑定整个对象到Model上
builder.Services.Configure<OptionsSetting>(builder.Configuration); builder.Services.Configure<OptionsSetting>(builder.Configuration);
builder.Configuration.AddJsonFile("codeGen.json");
builder.Configuration.AddJsonFile("iprate.json");
//jwt 认证 //jwt 认证
builder.Services.AddJwt(); builder.Services.AddJwt();
//配置文件 //配置文件

View File

@ -67,26 +67,6 @@
"AppID": "", "AppID": "",
"AppSecret": "" "AppSecret": ""
}, },
//
"gen": {
//
"showApp": false,
//
"autoPre": true,
"author": "admin",
"tablePrefix": "sys_", //"表前缀(生成类名不会包含表前缀,多个用逗号分隔)",
"vuePath": "", //egD:\Work\ZRAdmin-Vue3
"csharpTypeArr": {
"string": [ "varchar", "nvarchar", "text", "longtext" ],
"int": [ "int", "integer", "smallint", "int4", "int8", "int2" ],
"long": [ "bigint", "number" ],
"float": [ "numeric", "real", "float" ],
"decimal": [ "money", "decimal", "smallmoney" ],
"dateTime": [ "date", "datetime", "datetime2", "smalldatetime", "timestamp" ],
"byte": [ "tinyint" ],
"bool": [ "bit" ]
}
},
// //
"MailOptions": { "MailOptions": {
// //
@ -107,36 +87,20 @@
"Cache": "127.0.0.1:6379,defaultDatabase=0,poolsize=50,ssl=false,writeBuffer=10240,prefix=cache:", "Cache": "127.0.0.1:6379,defaultDatabase=0,poolsize=50,ssl=false,writeBuffer=10240,prefix=cache:",
"Session": "127.0.0.1:6379,defaultDatabase=0,poolsize=50,ssl=false,writeBuffer=10240,prefix=session:" "Session": "127.0.0.1:6379,defaultDatabase=0,poolsize=50,ssl=false,writeBuffer=10240,prefix=session:"
}, },
//
"IpRateLimiting": {
"EnableEndpointRateLimiting": true,
"StackBlockedRequests": false,
"RealIpHeader": "X-Real-IP",
"ClientIdHeader": "X-ClientId",
"HttpStatusCode": 429,
"EndpointWhitelist": [ "post:/system/dict/data/types", "*:/msghub/negotiate", "*:/LogOut", "*:/common/uploadfile", "*:/VerifyScan" ],
"QuotaExceededResponse": {
"Content": "{{\"code\":429,\"msg\":\"访问过于频繁,请稍后重试\"}}",
"ContentType": "application/json",
"StatusCode": 429
},
//api,*
"GeneralRules": [
{
"Endpoint": "*:/captchaImage",
//{}{}使s, m, h, d
"Period": "3s",
"Limit": 5
},
{
"Endpoint": "((post)|(put)):*",
"Period": "3s",
"Limit": 1
}
]
},
// //
"CaptchaOptions": { "CaptchaOptions": {
"IgnoreCase": true // "IgnoreCase": true //
},
//
"CodeGen": {
//
"showApp": false,
//
"autoPre": true,
//
"moduleName": "business",
"author": "admin",
"tablePrefix": "sys_", //"表前缀(生成类名不会包含表前缀,多个用逗号分隔)",
"vuePath": "" //egD:\Work\ZRAdmin-Vue3
} }
} }

View File

@ -0,0 +1,30 @@
{
//
"IpRateLimiting": {
"EnableEndpointRateLimiting": true,
"StackBlockedRequests": false,
"RealIpHeader": "X-Real-IP",
"ClientIdHeader": "X-ClientId",
"HttpStatusCode": 429,
"EndpointWhitelist": [ "post:/system/dict/data/types", "*:/msghub/negotiate", "*:/LogOut", "*:/common/uploadfile", "*:/VerifyScan" ],
"QuotaExceededResponse": {
"Content": "{{\"code\":429,\"msg\":\"访问过于频繁,请稍后重试\"}}",
"ContentType": "application/json",
"StatusCode": 429
},
//api,*
"GeneralRules": [
{
"Endpoint": "*:/captchaImage",
//{}{}使s, m, h, d
"Period": "3s",
"Limit": 5
},
{
"Endpoint": "((post)|(put)):*",
"Period": "3s",
"Limit": 1
}
]
}
}

View File

@ -113,14 +113,11 @@ $if(replaceDto.ShowBtnDelete || replaceDto.ShowBtnMultiDel)
[HttpDelete("{ids}")] [HttpDelete("{ids}")]
[ActionPermissionFilter(Permission = "${replaceDto.PermissionPrefix}:delete")] [ActionPermissionFilter(Permission = "${replaceDto.PermissionPrefix}:delete")]
[Log(Title = "${genTable.FunctionName}", BusinessType = BusinessType.DELETE)] [Log(Title = "${genTable.FunctionName}", BusinessType = BusinessType.DELETE)]
public IActionResult Delete${replaceDto.ModelTypeName}(string ids) public IActionResult Delete${replaceDto.ModelTypeName}([ModelBinder(typeof(CommaSeparatedArrayModelBinder<${replaceDto.PKType}>))] ${replaceDto.PKType}[] ids)
{ {
long[] idsArr = Tools.SpitLongArrary(ids); if (ids.Length <= 0) { return ToResponse(ApiResult.Error($"删除失败Id 不能为空")); }
if (idsArr.Length <= 0) { return ToResponse(ApiResult.Error($"删除失败Id 不能为空")); }
var response = _${replaceDto.ModelTypeName}Service.Delete(idsArr$if(replaceDto.enableLog), "删除${genTable.FunctionName}"$end); return ToResponse(_${replaceDto.ModelTypeName}Service.Delete(ids$if(replaceDto.enableLog), "删除${genTable.FunctionName}"$end));
return ToResponse(response);
} }
$end $end

View File

@ -0,0 +1,16 @@
using System.Collections.Generic;
namespace ZR.CodeGenerator.Model
{
public class ImportCodeGenTableDto
{
public string DbName { get; set; }
public List<CodeGenTables> Tables { get; set; }
}
public class CodeGenTables
{
public string Name { get; set; }
public string Description { get; set; }
}
}

View File

@ -0,0 +1,13 @@
using Infrastructure.Model;
namespace ZR.CodeGenerator.Model
{
public class InitTableDto
{
public string DbName { get; set; }
public string UserName { get; set; }
public string TableName { get; set; }
public string Desc { get; set; }
public CodeGen CodeGen { get; set; }
}
}