ASP.NET Core Web API - Swagger displays abnormal characters in Request Body

Viewed 42

In ASP.NET Core-6 Web API, I am implementing Swagger in Entity Framework Application. I use Data Annotation for the validation.

I have this model:

public class CreateUserDto
{
    [Required(ErrorMessage = "User Name field is required. ERROR!")]
    [StringLength(25, MinimumLength = 2, ErrorMessage = "User Name should be at least 2 characters long, but not longer than 25 characters.")]
    [RegularExpression(@"^[\S]+$", ErrorMessage = "No Space Required in User Name")]
    public string UserName { get; set; }

    [Required(ErrorMessage = "First Name field is required. ERROR!")]
    [StringLength(25, MinimumLength = 2, ErrorMessage = "First Name field should be at least 2 characters long, but not longer than 25 characters.")]
    [RegularExpression(@"^[A-Za-z][A-Za-z-\S]+$", ErrorMessage = "First Name field can only contain alphabets and No Space")]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "Last Name field is required. ERROR!")]
    [StringLength(25, MinimumLength = 2, ErrorMessage = "Last Name field should be at least 2 characters long, but not longer than 25 characters.")]
    [RegularExpression(@"^[A-Za-z][A-Za-z-\S]+$", ErrorMessage = "Last Name field can only contain alphabets and No Space")]
    public string LastName { get; set; }

    [Required(ErrorMessage = "Email field is required. ERROR!")]
    [StringLength(100, ErrorMessage = "Email field must not exceed 100 characters.")]
    [EmailAddress(ErrorMessage = "The Email field is not a valid e-mail address.")]
    public string Email { get; set; }

    [Required(ErrorMessage = "Role field is required. ERROR!")]
    public string Role { get; set; }

    [RegularExpression(@"^\+?([0-9]{3})?\)?0?([0-9]{10})$", ErrorMessage = "Mobile number format should either be +239xxxxxxxxxxx or 0xxxxxxxxxx. ERROR!")]
    public string MobileNumber { get; set; }

    [StringLength(500, ErrorMessage = "Description field must not exceed 500 characters.")]
    public string Description { get; set; }
}

Swagger RequestBody:

{
  "userName": "o4Q8~Rd!1THgt\"Uj1TR-'+^mC",
  "firstName": "b$^;vX}G'<mOrO)38='r^mBv?",
  "lastName": "c\\e\\z^zYnD)-mFG#h>SI<jZmp",
  "email": "user@example.com",
  "role": "string",
  "mobileNumber": "09608460202",
  "description": "string"
}

In the Swagger RequestBody, I observed that all the fields (userName, firstName, lastName and mobileNumber) where I used Regular Expression displays abnormal characters instead of the data type e.g string.

What could have caused this and how do I resolve it?

Thanks

0 Answers
Related