.Net Core3.0 WEB API中使用FluentValidation驗(yàn)證(批量注入)
為什么要使用FluentValidation
1.在日常的開(kāi)發(fā)中,需要驗(yàn)證參數(shù)的合理性,不緊前端需要驗(yàn)證傳毒的參數(shù),后端也需要驗(yàn)證參數(shù)
2.在領(lǐng)域模型中也應(yīng)該驗(yàn)證,做好防御性的編程是一種好的習(xí)慣(其實(shí)以前重來(lái)不寫(xiě)的,被大佬教育了一番)
3.FluentValidation 是.NET 開(kāi)發(fā)的驗(yàn)證框架,開(kāi)源,主要是簡(jiǎn)單好用,內(nèi)置了一些常用的驗(yàn)證器,可以直接使用,擴(kuò)展也很方便
使用FluentValidation
1.引入FluentValidation.AspNetCore NuGet包
2.建立需要驗(yàn)證的類
/// <summary>
/// 創(chuàng)建客戶
/// </summary>
public class CreateCustomerDto
{
/// <summary>
/// 客戶姓名
/// </summary>
public string CustomerName { get; set; }
/// <summary>
/// 客戶年齡
/// </summary>
public string CustomerAge { get; set; }
/// <summary>
/// 客戶電話
/// </summary>
public string CustomerPhone { get; set; }
/// <summary>
/// 客戶地址
/// </summary>
public Address CustomerAddress { get; set; }
}
/// <summary>
/// 驗(yàn)證
/// </summary>
public class CreateCustomerDtoValidator : AbstractValidator<CreateCustomerDto>
{
public CreateCustomerDtoValidator()
{
RuleFor(x => x.CustomerName)
.NotEmpty()
.WithMessage("客戶姓名不能為空");
RuleFor(x => x.CustomerPhone)
.NotEmpty()
.WithMessage("客戶電話不能為空");
}
}
3.統(tǒng)一返回驗(yàn)證的信息,ResponseResult為全局統(tǒng)一參數(shù)返回的類
/// <summary>
/// 添加AddFluentValidationErrorMessage
/// </summary>
/// <returns></returns>
public DependencyInjectionService AddFluentValidationErrorMessage()
{
_services.Configure<ApiBehaviorOptions>(options =>
{
options.InvalidModelStateResponseFactory = (context) =>
{
var errors = context.ModelState
.Values
.SelectMany(x => x.Errors
.Select(p => p.ErrorMessage))
.ToList();
var result = new ResponseResult<List<string>>
{
StatusCode = "00009",
Result = errors,
Message = string.Join(",", errors.Select(e => string.Format("{0}", e)).ToList()),
IsSucceed = false
};
return new BadRequestObjectResult(result);
};
});
return _dependencyInjectionConfiguration;
}
4.注入驗(yàn)證的類
使用builder.RegisterType().As<IValidator>();比較麻煩每次新增都需要添加一次注入
所以我們使用批量的注入,來(lái)減少麻煩,通過(guò)反射獲取所有的驗(yàn)證的類批量注入
/// <summary>
/// 添加MVC
/// </summary>
/// <returns></returns>
public DependencyInjectionService AddMvc()
{
_services.AddControllers(options =>
{
options.Filters.Add(typeof(LogHelper));
}).AddJsonOptions(options =>
{
//忽略循環(huán)引用
//options.JsonSerializerOptions.IgnoreReadOnlyProperties = true;
}).AddFluentValidation(options =>
{
options.RunDefaultMvcValidationAfterFluentValidationExecutes = false;
var validatorList = GetFluentValidationValidator("ConferenceWebApi");
foreach (var item in validatorList)
{
options.RegisterValidatorsFromAssemblyContaining(item);
}
});
return _dependencyInjectionConfiguration;
}
/// <summary>
/// 獲取所有的FluentValidation Validator的類
/// </summary>
public IEnumerable<Type> GetFluentValidationValidator(string assemblyName)
{
if (assemblyName == null)
throw new ArgumentNullException(nameof(assemblyName));
if (string.IsNullOrEmpty(assemblyName))
throw new ArgumentNullException(nameof(assemblyName));
var implementAssembly = RuntimeHelper.GetAssembly(assemblyName);
if (implementAssembly == null)
{
throw new DllNotFoundException($"the dll ConferenceWebApi not be found");
}
var validatorList = implementAssembly.GetTypes().Where(e => e.Name.EndsWith("Validator"));
return validatorList;
}
5.使用起來(lái)就十分簡(jiǎn)單了
/// <summary>
/// 創(chuàng)建客戶
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[HttpPost]
public async Task<ResponseResult<string>> CreateCustomer([FromBody] CreateCustomerDto input)
{
var createCustomerCommand = new CreateCustomerCommand(input.CustomerName,input.CustomerAge,input.CustomerPhone,input.CustomerAddress);
await _commandService.SendCommandAsync(createCustomerCommand);
var result = new ResponseResult<string>
{
IsSucceed = true,
Result = "創(chuàng)建客戶成功!"
};
return result;
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
創(chuàng)建一個(gè)ASP.NET MVC5項(xiàng)目的實(shí)現(xiàn)方法(圖文)
這篇文章主要介紹了創(chuàng)建一個(gè)ASP.NET MVC 5項(xiàng)目,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
asp.net在iframe中彈出信息并執(zhí)行跳轉(zhuǎn)問(wèn)題探討
本代碼將實(shí)現(xiàn)在iframe中彈出信息并執(zhí)行跳轉(zhuǎn),感興趣的朋友可以參考下2013-04-04
.NET 6開(kāi)發(fā)TodoList應(yīng)用之實(shí)現(xiàn)數(shù)據(jù)塑形
在查詢的場(chǎng)景中,還有一類需求不是很常見(jiàn),就是在前端請(qǐng)求中指定返回的字段。所以這篇文章主要介紹了.NET 6如何實(shí)現(xiàn)數(shù)據(jù)塑形,需要的可以參考一下2022-01-01
asp.net 將設(shè)有過(guò)期策略的項(xiàng)添加到緩存中
調(diào)用 Insert 方法,將絕對(duì)過(guò)期時(shí)間或彈性過(guò)期時(shí)間傳遞給該方法。2009-04-04
.NET中讀取Excel文件的數(shù)據(jù)及excelReader應(yīng)用
輕量,快速的C#編寫(xiě)的庫(kù)讀取Microsoft Excel文件,這對(duì)讀取大量excel文件的朋友們很有幫助而且可以學(xué)習(xí)下ExcelDataReader的應(yīng)用,感興趣的朋友可以了解下,或許對(duì)你有所幫助2013-02-02
使用.Net?Core實(shí)現(xiàn)的一個(gè)圖形驗(yàn)證碼功能
SimpleCaptcha是一個(gè)使用簡(jiǎn)單,基于.Net Standard 2.0的圖形驗(yàn)證碼模塊。這篇文章主要介紹了使用.Net?Core實(shí)現(xiàn)的一個(gè)圖形驗(yàn)證碼功能,需要的朋友可以參考下2021-12-12
ASP.NET動(dòng)態(tài)加載用戶控件的實(shí)現(xiàn)方法
動(dòng)態(tài)加載用戶控件的方法,用asp.net的朋友推薦2008-10-10
Asp.net開(kāi)發(fā)常用的51個(gè)非常實(shí)用的代碼
Asp.net開(kāi)發(fā)常用的51個(gè)非常實(shí)用的代碼,需要的朋友可以參考下。2010-06-06

