• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

ASP .NET Core FluentValidation

Sascha Оффлайн

Sascha

Заместитель Администратора
Команда форума
Администратор
Регистрация
9 Май 2015
Сообщения
1,549
Баллы
155

Introduction


The best NuGet package for validating data for C# for any project type is FluentValidation. The focus here is on transitioning from the NuGet package for ASP.NET Core FluentValidation.AspNetCore, which has been deprecated, is now using two different packages, adding a language extension, if used, one or more enum members.

Tools used



Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



Scenario


A developer has a Microsoft Visual Studio solution that contains one or more projects for presenting information in an ASP.NET Core project, which uses the deprecated NuGet package FluentValidation.AspNetCore. The task is to move away from the deprecated NuGet package.

Preparation

  • Ensure current code compiles and functions
  • Perform a commit to a remote repository

🛑 From this point on, do not commit any changes until the code functions during the Migration.

Migration steps


Open each project file by clicking on the file in Microsoft Visual Studio's solution explorer, and remove the following.


<ItemGroup>
<PackageReference Include="FluentValidation.AspNetCore" Version="11.3.1" />
</ItemGroup>




Add the following. Next open dependency window and check for upgrades.


<ItemGroup>
<PackageReference Include="FluentValidation" Version="12.0.0" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="12.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.3.0" />
</ItemGroup>



Build


For this build, expect errors; address the easy errors first, such as invalid using statements. Depending on what has been used exclusively with FluentValidation.AspNetCore, like the following CascadeMode.StopOnFirstFailure will not exist; instead, use CascadeMode.Stop.

There may be extensions and methods that do not exists such as AddToModelState which need to have replacements as shown below.


public static void AddToModelState(this ValidationResult result, ModelStateDictionary modelState, string prefix)
{

if (result.IsValid) return;

foreach (var error in result.Errors)
{
string key = string.IsNullOrEmpty(prefix)
? error.PropertyName
: string.IsNullOrEmpty(error.PropertyName)
? prefix
: $"{prefix}.{error.PropertyName}";
modelState.AddModelError(key, error.ErrorMessage);
}
} public static void AddToModelState(this ValidationResult result, ModelStateDictionary modelState, string prefix)
{

if (result.IsValid) return;

foreach (var error in result.Errors)
{
string key = string.IsNullOrEmpty(prefix)
? error.PropertyName
: string.IsNullOrEmpty(error.PropertyName)
? prefix
: $"{prefix}.{error.PropertyName}";
modelState.AddModelError(key, error.ErrorMessage);
}
}




Continue fixing build errors until a clean build is achieved, followed by testing all functionality. Once satisfied, commit your changes.

Summary
What has been presented should be sufficient to perform the migration, although there may be fringe cases that require the same handling as shown here.



Источник:

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу