在业务层实现校验请求参数
生活随笔
收集整理的這篇文章主要介紹了
在业务层实现校验请求参数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言
在前面的文章中,我們介紹了在業務層實現管道模式:
響應緩存
記錄請求日志
今天,我們同樣使用IPipelineBehavior,介紹如何在業務層實現校驗請求參數,用于檢查輸入是否滿足業務要求。
Demo
首先,創建ASP.NET Core Web API項目,引用Nuget包:
MediatR MediatR.Extensions.Microsoft.DependencyInjection FluentValidation FluentValidation.DependencyInjectionExtensions1.實現IPipelineBehavior
創建ValidationBehaviour,用于校驗請求參數:
public?class?ValidationBehaviour<TRequest,?TResponse>?:?IPipelineBehavior<TRequest,?TResponse>where?TRequest?:?IRequest<TResponse> {private?readonly?IEnumerable<IValidator<TRequest>>?_validators;public?ValidationBehaviour(IEnumerable<IValidator<TRequest>>?validators){_validators?=?validators;}public?async?Task<TResponse>?Handle(TRequest?request,?CancellationToken?cancellationToken,RequestHandlerDelegate<TResponse>?next){//?如果沒有為當前正在執行的請求定義校驗器,則退出if?(!_validators.Any())?return?await?next();//?執行校驗器var?context?=?new?ValidationContext<TRequest>(request);var?validationResults?=await?Task.WhenAll(_validators.Select(v?=>?v.ValidateAsync(context,?cancellationToken)));var?errors?=?validationResults.SelectMany(r?=>?r.Errors).Where(f?=>?f?!=?null).ToList();if?(!errors.Any())?return?await?next();//?返回錯誤var?sb?=?new?StringBuilder();errors.ForEach(f?=>{sb.Append(f.ErrorMessage);});throw?new?Exception(sb.ToString());} }2.注冊IPipelineBehavior
修改Startup.cs:
services.AddValidatorsFromAssembly(typeof(Startup).Assembly);services.AddMediatR(typeof(Startup).Assembly); services.AddTransient(typeof(IPipelineBehavior<,>),?typeof(ValidationBehaviour<,>))3.測試
修改WeatherForecastController,使用Mediator:
public?class?WeatherForecastController?:?ControllerBase {private?readonly?IMediator?_mediator;public?WeatherForecastController(IMediator?mediator){this._mediator?=?mediator;}[HttpGet]public?async?Task<IEnumerable<WeatherForecast>>?Get(int?count){return?await?this._mediator.Send(new?GetWeatherForecastQuery?{?Count=?count?});} }public?class?GetWeatherForecastQuery?:?IRequest<IEnumerable<WeatherForecast>> {public?int?Count?{?get;?set;?} }internal?class?GetWeatherForecastQueryHandler?:?IRequestHandler<GetWeatherForecastQuery,?IEnumerable<WeatherForecast>> {?public?async?Task<IEnumerable<WeatherForecast>>?Handle(GetWeatherForecastQuery?request,?CancellationToken?cancellationToken){var?rng?=?new?Random();return?Enumerable.Range(1,?request.Count).Select(index?=>?new?WeatherForecast{TemperatureC?=?rng.Next(-20,?55),}).ToArray();} }并為GetWeatherForecastQuery創建一個Validator,校驗Count參數的取值范圍:
public?class?GetWeatherForecastQueryValidator?:?AbstractValidator<GetWeatherForecastQuery> {public?GetWeatherForecastQueryValidator(){RuleFor(c?=>?c.Count).GreaterThanOrEqualTo(1).WithMessage("Count的取值范圍是1到5").LessThanOrEqualTo(5).WithMessage("Count的取值范圍是1到5");} }運行程序,輸入錯誤值,將拋出異常:
結論
在本文中,我們通過FluentValidation實現校驗功能,詳細使用方式請參看官網:https://fluentvalidation.net/
如果你覺得這篇文章對你有所啟發,請關注我的個人公眾號”My IO“
總結
以上是生活随笔為你收集整理的在业务层实现校验请求参数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何实现 asp.net core 安全
- 下一篇: 如何在 Entity Framework