Skip to main content
.NETCoreApp3.1

Package Description

Published
Aug 16, 2023
3y ago
Total Downloads
7.0K
7,023

Install

dotnet add package Byndyusoft.ValidEnumConverter --version 1.1.1
ProductVersions
Other
.NETCoreApp3.1

README

Byndyusoft.ValidEnumConverter

Custom JsonConverter for enums with value validation.

Byndyusoft.ValidEnumConverter Nuget Downloads

Installing

dotnet add package Byndyusoft.ValidEnumConverter

Usage

Byndyusoft.ValidEnumConverter designed to properly validate numbers in a string. The System.Text.Json.Serialization library does not correctly validate numbers in a string like "Enum" For example: We have our own enum, let's call it UserRole:

public enum UserRole
{
    Administrator = 0,
    Agent = 1
}

And there is a Dto object:

public UserInfoDto 
{
    public int Id {get; set; }
    public UserRole Role {get; set; }
}

When using this Dto object in our controller as an accepted class On the front side, the following Json can be sent:

{
  "Id": 1,
  "UserRole": "589"
}

The non-existent value of our UserRole, it is logical to assume that a regular validator should throw an error with a code of 400, but this does not happen. Therefore, we decided to make our own custom converter. Which validates the numbers in the string correctly

how to use the converter We go to the Setup.cs of our project:

services.AddControllers ()
    .AddJsonOptions (options => ...

and add following line

options.JsonSerializerOptions.Converters.AddValidEnumConverter();

After that, all Enum types are correctly converted for you.

Contributing

To contribute, you will need to setup your local environment, see prerequisites. For the contribution and workflow guide, see package development lifecycle.

A detailed overview on how to contribute can be found in the contributing guide.

Prerequisites

Make sure you have installed all of the following prerequisites on your development machine:

Package development lifecycle

  • Implement package logic

Maintainers

[email protected]

Changes from Previous Version

No structural changes between v1.1.0 and v1.1.1.

Adoption Assessment

Assess this package against its supported frameworks, license, maintenance signals and dependency graph before making it a project standard.

No SPDX license expression is published. Review the license text and your organisation's policy before redistribution.Compatibility metadata lists 1 target framework; confirm the exact target used by your application.

Related Guides & Workflows

Learn how to evaluate, integrate, or audit this package in your .NET project.