日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

.NET?6開發(fā)TodoList應(yīng)用之實(shí)現(xiàn)接口請求驗(yàn)證_實(shí)用技巧

作者:CODE4NOTHING ? 更新時(shí)間: 2022-03-20 編程語言

需求

在響應(yīng)請求處理的過程中,我們經(jīng)常需要對請求參數(shù)的合法性進(jìn)行校驗(yàn),如果參數(shù)不合法,將不繼續(xù)進(jìn)行業(yè)務(wù)邏輯的處理。我們當(dāng)然可以將每個(gè)接口的參數(shù)校驗(yàn)邏輯寫到對應(yīng)的Handle方法中,但是更好的做法是借助MediatR提供的特性,將這部分與實(shí)際業(yè)務(wù)邏輯無關(guān)的代碼整理到單獨(dú)的地方進(jìn)行管理。

為了實(shí)現(xiàn)這個(gè)需求,我們需要結(jié)合FluentValidation和MediatR提供的特性。

目標(biāo)

將請求的參數(shù)校驗(yàn)邏輯從CQRS的Handler中分離到MediatR的Pipeline框架中處理。

原理與思路

MediatR不僅提供了用于實(shí)現(xiàn)CQRS的框架,還提供了IPipelineBehavior<TRequest, TResult>接口用于實(shí)現(xiàn)CQRS響應(yīng)之前進(jìn)行一系列的與實(shí)際業(yè)務(wù)邏輯不緊密相關(guān)的特性,諸如請求日志、參數(shù)校驗(yàn)、異常處理、授權(quán)、性能監(jiān)控等等功能。

在本文中我們將結(jié)合FluentValidation和IPipelineBehavior<TRequest, TResult>實(shí)現(xiàn)對請求參數(shù)的校驗(yàn)功能。

實(shí)現(xiàn)

添加MediatR參數(shù)校驗(yàn)Pipeline Behavior框架支持#

首先向Application項(xiàng)目中引入FluentValidation.DependencyInjectionExtensionsNuget包。為了抽象所有的校驗(yàn)異常,先創(chuàng)建ValidationException類:

ValidationException.cs

namespace TodoList.Application.Common.Exceptions;

public class ValidationException : Exception
{
    public ValidationException() : base("One or more validation failures have occurred.")
    {
    }

    public ValidationException(string failures)
        : base(failures)
    {
    }
}

參數(shù)校驗(yàn)的基礎(chǔ)框架我們創(chuàng)建到Application/Common/Behaviors/中:

ValidationBehaviour.cs

using FluentValidation;
using FluentValidation.Results;
using MediatR;
using ValidationException = TodoList.Application.Common.Exceptions.ValidationException;

namespace TodoList.Application.Common.Behaviors;

public class ValidationBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
    where TRequest : notnull
{
    private readonly IEnumerable<IValidator<TRequest>> _validators;

    // 注入所有自定義的Validators
    public ValidationBehaviour(IEnumerable<IValidator<TRequest>> validators) 
        => _validators = validators;

    public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
    {
        if (_validators.Any())
        {
            var context = new ValidationContext<TRequest>(request);

            var validationResults = await Task.WhenAll(_validators.Select(v => v.ValidateAsync(context, cancellationToken)));

            var failures = validationResults
                .Where(r => r.Errors.Any())
                .SelectMany(r => r.Errors)
                .ToList();

            // 如果有validator校驗(yàn)失敗,拋出異常,這里的異常是我們自定義的包裝類型
            if (failures.Any())
                throw new ValidationException(GetValidationErrorMessage(failures));
        }
        return await next();
    }

    // 格式化校驗(yàn)失敗消息
    private string GetValidationErrorMessage(IEnumerable<ValidationFailure> failures)
    {
        var failureDict = failures
            .GroupBy(e => e.PropertyName, e => e.ErrorMessage)
            .ToDictionary(failureGroup => failureGroup.Key, failureGroup => failureGroup.ToArray());

        return string.Join(";", failureDict.Select(kv => kv.Key + ": " + string.Join(' ', kv.Value.ToArray())));
    }
}

在DependencyInjection中進(jìn)行依賴注入:

DependencyInjection.cs

// 省略其他...
services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly());
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehaviour<,>) 

添加Validation Pipeline Behavior

接下來我們以添加TodoItem接口為例,在Application/TodoItems/CreateTodoItem/中創(chuàng)建CreateTodoItemCommandValidator:

CreateTodoItemCommandValidator.cs

using FluentValidation;
using Microsoft.EntityFrameworkCore;
using TodoList.Application.Common.Interfaces;
using TodoList.Domain.Entities;

namespace TodoList.Application.TodoItems.Commands.CreateTodoItem;

public class CreateTodoItemCommandValidator : AbstractValidator<CreateTodoItemCommand>
{
    private readonly IRepository<TodoItem> _repository;

    public CreateTodoItemCommandValidator(IRepository<TodoItem> repository)
    {
        _repository = repository;

        // 我們把最大長度限制到10,以便更好地驗(yàn)證這個(gè)校驗(yàn)
        // 更多的用法請參考FluentValidation官方文檔
        RuleFor(v => v.Title)
            .MaximumLength(10).WithMessage("TodoItem title must not exceed 10 characters.").WithSeverity(Severity.Warning)
            .NotEmpty().WithMessage("Title is required.").WithSeverity(Severity.Error)
            .MustAsync(BeUniqueTitle).WithMessage("The specified title already exists.").WithSeverity(Severity.Warning);
    }

    public async Task<bool> BeUniqueTitle(string title, CancellationToken cancellationToken)
    {
        return await _repository.GetAsQueryable().AllAsync(l => l.Title != title, cancellationToken);
    }
}

其他接口的參數(shù)校驗(yàn)添加方法與此類似,不再繼續(xù)演示。

驗(yàn)證

啟動Api項(xiàng)目,我們用一個(gè)校驗(yàn)會失敗的請求去創(chuàng)建TodoItem:

請求

響應(yīng)

因?yàn)橹皽y試的時(shí)候已經(jīng)在沒有加校驗(yàn)的時(shí)候用同樣的請求生成了一個(gè)TodoItem,所以校驗(yàn)失敗的消息里有兩項(xiàng)校驗(yàn)都沒有滿足。

一點(diǎn)擴(kuò)展

我們在前文中說了使用MediatR的PipelineBehavior可以實(shí)現(xiàn)在CQRS請求前執(zhí)行一些邏輯,其中就包含了日志記錄,這里就把實(shí)現(xiàn)方式也放在下面,在這里我們使用的是Pipeline里的IRequestPreProcessor<TRequest>接口實(shí)現(xiàn),因?yàn)橹魂P(guān)心請求處理前的信息,如果關(guān)心請求處理返回后的信息,那么和前文一樣,需要實(shí)現(xiàn)IPipelineBehavior<TRequest, TResponse>接口并在Handle中返回response對象:

// 省略其他...
var response = await next();
//Response
_logger.LogInformation($"Handled {typeof(TResponse).Name}");

return response;

創(chuàng)建一個(gè)LoggingBehavior:

using System.Reflection;
using MediatR.Pipeline;
using Microsoft.Extensions.Logging;

public class LoggingBehaviour<TRequest> : IRequestPreProcessor<TRequest> where TRequest : notnull
{
    private readonly ILogger<LoggingBehaviour<TRequest>> _logger;

    // 在構(gòu)造函數(shù)中后面我們還可以注入類似ICurrentUser和IIdentity相關(guān)的對象進(jìn)行日志輸出
    public LoggingBehaviour(ILogger<LoggingBehaviour<TRequest>> logger)
    {
        _logger = logger;
    }

    public async Task Process(TRequest request, CancellationToken cancellationToken)
    {
        // 你可以在這里log關(guān)于請求的任何信息
        _logger.LogInformation($"Handling {typeof(TRequest).Name}");

        IList<PropertyInfo> props = new List<PropertyInfo>(request.GetType().GetProperties());
        foreach (var prop in props)
        {
            var propValue = prop.GetValue(request, null);
            _logger.LogInformation("{Property} : {@Value}", prop.Name, propValue);
        }
    }
}

如果是實(shí)現(xiàn)IPipelineBehavior<TRequest, TResponse>接口,最后注入即可。

// 省略其他...
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(LoggingBehaviour<,>));

如果實(shí)現(xiàn)IRequestPreProcessor<TRequest>接口,則不需要再進(jìn)行注入。

效果如下圖所示:

可以看到日志中已經(jīng)輸出了Command名稱和請求參數(shù)字段值。

總結(jié)

在本文中我們通過FluentValidation和MediatR實(shí)現(xiàn)了不侵入業(yè)務(wù)代碼的請求參數(shù)校驗(yàn)邏輯,在下一篇文章中我們將介紹.NET開發(fā)中會經(jīng)常用到的ActionFilters。

參考資料

FluentValidation

How to use MediatR Pipeline Behaviours?

原文鏈接:https://www.cnblogs.com/code4nothing/p/15743335.html

欄目分類
最近更新