How do I create a custom validation message on a model passed into a controller action method of a c# web API?
Here is the model:
[DataContract]
public class TestDto //: IValidatableObject
{
[DataMember]
[LongValidation("Its not a long!")]
public long? ID { get; set; }
[DataMember]
public string Description { get; set; }
public string DescriptionHidden { get; set; }
}
Here is my controller class:
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public string Post([FromBody]TestDto testDto)
{
//todo: should a post return any data?
if (ModelState.IsValid)
return "success!";
else
{
var ret = string.Empty;
foreach (var modelState in ModelState)
{
ModelErrorCollection errorCollection = modelState.Value.Errors;
var errors = string.Empty;
foreach (var error in errorCollection)
{
errors = errors + "exception message: " + error.Exception.Message + ", errorMessage: " + error.ErrorMessage;
}
ret = ret + "Error: " + modelState.Key + ", " + modelState.Value.Value + ", errors: " + errors;
}
return ret;
}
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
If I post this object into the Post action:
{
"ID" : "1aaa","Description": "sample string 2",
}
In my LongValidation's valid method, I get the default value for a long not : "1aaa", so I cannot perform the correct validation in the validator.
Here is the code for the Long Validator:
public class LongValidationAttribute : ValidationAttribute
{
public LongValidationAttribute(string errorMessage) : base(errorMessage)
{
}
public override string FormatErrorMessage(string name)
{
return base.FormatErrorMessage(name);
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
long ret;
bool success = long.TryParse(value.ToString(), out ret);
//return base.IsValid(value, validationContext);
if (success == false)
return new ValidationResult(this.ErrorMessage);
else
{
return ValidationResult.Success;
}
}
}