The reason why you are getting 0 is because string can't be mapped to int, so it just leaves a default value (which is zero). To validate users input you can use attributes.
Try something like this:
public class RequestModel
{
[Range(1, int.MaxValue, ErrorMessage = "*Your warning*")]
public int Code { set; get; }
}
Than in your controller you can check if model state is valid and respond properly. Basically in the beginning of your method in controller you should write something like this:
if(!ModelState.IsValid)
{
// Return errors for example
}
else
{
// Something else
}
There is a more elegant way to do such kind of validation. You can simply make your field nullable (int?
) and delegate all validation work to fluent validator. It will run the validation before you'll get in controller and automatically return BadRequest if something goes wrong. Example of fluent validator for your model:
public class RequestModelValidator : AbstractValidator<RequestModel>
{
public RequestModelValidator()
{
RuleFor(m => m.Code).NotNull().WithMessage("*Your msg*");
}
}