0

I am working on a test ASP.NET Core 2.0 service to expand my programming knowledge to include server side experience. I have a Registration Model class that is sent to the service when a user is registering in my application. My RegistrationModel class is below:

public class RegistrationModel
{
    [Required]
    public string Username { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    [Required]
    [EmailAddress]
    public string Email { get; set; }
    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    public string Password { get; set; }
    [Required]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
}

The RegisterUser method I am calling is below. I am POSTing the data to the service and retrieving it from the Body of the call.

[HttpPost(nameof(RegisterUser))]
[AllowAnonymous]
public async Task<IActionResult> RegisterUser([FromBody] RegistrationModel registrationInfo)

When sending the JSON to the service, the ModelState.IsValid is always true unless I send a null object. If I send a completely empty object, the ModelState.IsValid is still true. I've also tried the to remove the [FromBody] from the parameter list for the method and that didn't change anything.

Is there some option that needs to be set in the startup.cs file to validate the models automatically or is there manual validation I need to perform myself? If I need to provide any other information, just let me know.

CraftyCoder
  • 55
  • 1
  • 7

2 Answers2

1

In my service I was calling services.AddMvcCore() rather than services.AddMvc() since this is strictly an Api and won't have a web facing view.

When using services.AddMvcCore() you must specify a lot of the features that services.AddMvc() provides by default. One feature I was not specifying was .AddDataAnnotations(). Adding that to my existing call of services.AddMvcCore().AddJsonFormatters().AddAuthorization=(...) fixed everything.

CraftyCoder
  • 55
  • 1
  • 7
0

Model validation is enabled out of the box.

I created a new project based on the ASP.NET Core 2.0 template provided by Visual Studio, and it worked fine.

Here's the implementation of the action:

public Task<IActionResult> Register([FromBody] RegistrationModel model)
{
    return Task.FromResult<IActionResult>(Ok(new { ModelState.IsValid, ModelState.Values }));
}

Sending the following JSON:

{
    "Username": "Mick",
    "FirstName": "Mick",
    "LastName": "Mick",
    "Email": "mick@mick.com",
    "Password": "MickMick",
    "ConfirmPassword": "MickMick"
}

produced:

{
    "isValid": true,
    "values": []
}

However, sending the following payload:

{
    "Username": "Mick",
    "FirstName": "",
    "LastName": "Mick",
    "Email": "",
    "Password": "MickMick",
    "ConfirmPassword": ""
}

produced the following response:

{
  "isValid": false,
  // some properties omitted for brevity
  "values": [
    {
      "key": "Email",
      "errors": [
        {
          "errorMessage": "The Email field is required."
        }
      ]
    },
    {
      "key": "FirstName",
      "errors": [
        {
          "errorMessage": "The FirstName field is required."
        }
      ]
    },
    {
      "key": "ConfirmPassword",
      "errors": [
        {
          "errorMessage": "The ConfirmPassword field is required."
        },
        {
          "errorMessage": "The password and confirmation password do not match."
        }
      ]
    }
  ]
}

Could you describe how you hit the endpoint and exactly what payload you're sending in the request?

Mickaël Derriey
  • 12,796
  • 1
  • 53
  • 57
  • I am using Postman to test the calls for now. { "Username": "Mick", "FirstName": "", "LastName": "Mick", "Email": "", "Password": "MickMick", "ConfirmPassword": "" } This was the second payload I tried after a correct solution. Both came back true. – CraftyCoder Apr 12 '18 at 03:43
  • So i created a new solution and am trying the same call and it is working for me also now. I swear the model validation was working in the other solution before. Idk how I seemed to screw it up, but somehow I must have. – CraftyCoder Apr 12 '18 at 04:09