MVC WebAPI Data Annotation Error Message Empty String

I have implemented the standalone OWIN web application and am trying to use data annotations and ActionFilterAttribute to return formatted errors to the user. I have set custom error messages in data annotation, but when I try to get a message from ModelState, it is always an empty string (shown in the image below).

enter image description here

Model:

public class JobPointer
{
    [Required(ErrorMessage = "JobId Required")]
    public Guid JobId { get; set; }
}

Filter:

public class ModelValidationFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (actionContext.ModelState.IsValid) return;
        string errors = actionContext.ModelState.SelectMany(state => state.Value.Errors).Aggregate("", (current, error) => current + (error.ErrorMessage + ". "));

        actionContext.Response = actionContext.Request.CreateErrorResponse(
            HttpStatusCode.BadRequest, errors);
    }

}

end point:

[HttpPost]
public HttpResponseMessage DescribeJob(JobPointer jobId)
{

   Job job = _jobhelper.GetJob(jobId.JobId);
   return Request.CreateResponse(HttpStatusCode.OK, job);
}

Request body:

{

}

Answer:

Status Code: 400
{
  "Message": ". "
}

If I change error.Message in ModelValidationFilter to error.Exception.Message I return a default validation error:

Status Code: 400
{
  "Message": "Required property 'JobId' not found in JSON. Path '', line 3, position 2.. "
}
+4
source share
1 answer

, , .

, , , Guid [Required], ( , JSON ).

, Guid...

public class JobPointer
{
    [Required(ErrorMessage = "JobId Required")]
    public Guid? JobId { get; set; }
}

... , ( ), , . ...

public class IsNotEmptyAttribute : ValidationAttribute
{

    public override bool IsValid(object value)
    {

        if (value == null) return false;

        var valueType = value.GetType();
        var emptyField = valueType.GetField("Empty");

        if (emptyField == null) return true;

        var emptyValue = emptyField.GetValue(null);

        return !value.Equals(emptyValue);

    }
}

...

public class JobPointer
{
    [IsNotEmpty(ErrorMessage = "JobId Required")]
    public Guid JobId { get; set; }
}
+1

All Articles