0

In ASP.NET Web API I want to include a valid field when returning errors to the caller.

public class User 
{
    [Required(ErrorMessage = "ThirdPartyID is required!")]
    public int ThirdPartyID { get; set; }
    [Required(ErrorMessage = "Firstname is required!")]
    public string Firstname { get; set; }
    [Required(ErrorMessage = "Lastname is required!")]
    public string Lastname { get; set; }
}

When the caller posts a user with the ThirdParyID set, and the Firstname set, but without the Lastname, I want to add the ThirdPartyID to the response. I am using the below for Model Validation.

public class ModelValidationFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (actionContext.ModelState.IsValid == false)
        {
            actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
        }
    }
}

Is there something I can set on the User to indicate that the ThirdPartyID should always be included in the returned error messages?

tom
  • 1,822
  • 4
  • 25
  • 43
  • I'm having trouble understanding your business requirement. Is ThirdPartyId required or isn't it? – Youssef Moussaoui Feb 05 '13 at 10:56
  • We can say it is. But I still want to return it in the error message even if it is sent by the consumer of the API during the post. – tom Feb 05 '13 at 15:00

1 Answers1

0

You can use the ModelState.AddModelError method.

ModelState.AddModelError("VariableName", "Error Message");
Pat Burke
  • 580
  • 4
  • 13
  • That's fine if I'm doing validation inside the controller, but I want to do it in ModelValidationFilterAttribute : ActionFilterAttribute and for different models the valid field I want to return will vary. – tom Feb 04 '13 at 17:57