Send a Bad Request via REST

0

My method takes the field value. If this field is null or zero, a Bad Request must be sent to the user indicating the field ID and informing that it can not be null. This is a REST service. I'm setting up the code (a foreach) and inside that foreach it will spit these BAD REQUEST if there is. How do I generate a bad request within a rest?

    
asked by anonymous 15.03.2018 / 22:37

1 answer

1

MVC already does the automatic model validation for you. To get the errors of your model you can access the ModelState property. Example:

var errors = string.join(" ", ModelState.SelectMany(s => s.Value.Errors)
    .Select(e => e.ErrorMessage))
if(errors.Length > 0){
    return BadRequest(errors);
}

To display user-friendly messages you must set the ErrorMessage property to its validation attributes in your template. Example:

public class Modelo {
    [StringLength(1, ErrorMessage = "Introduza um nome válido")]
    public string Name{get;set;}
}

If this is not enough for you. You can always validate the model programmatically to know what the errors are. Example:

var context = new ValidationContext(model, null, null);
var results = new List<ValidationResult>();

bool valid = Validator.TryValidateObject(model, context, results, true);
if (valid)
{
    return Task.CompletedTask;
}

var errors = string.Join(" ", results.Select(e => e.ErrorMessage));
throw new InvalidOperationException($"Can not insert because data is not valid. {errors}");
    
16.03.2018 / 17:39