[Edit: the original code snippets were not correct.]
[This post is intented to help answer the specific question I had which I found a great answer to. I am linking to my example post that I followed and then the post that gave me the answer. Then I am posting the code that I used successfully to produce the results I achieved.]
I implemented a simple technique for Validation in my input to an ApiController. The following code was functional, but as you can see it only provided a generic error message.
The answer I found to guide me to this technique is found here: https://stackoverflow.com/a/19322688/7637275
The following is my code that I started with -
using System.Web.Http;
using System.Web.Routing;
using System.Web.Http.Controllers;
using System.Web;
using System.Web.Http.Filters;
namespace TestValidation
{
internal class ValidateModelStateFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
throw new HttpException(422, "Validation failed on input");
}
}
}
}
The following snippet shows the validation error I needed to see, instead of the generic message noted above.
[Required(ErrorMessage = @"Parameter ""ID"" is required.")]
[MaxLength(18, ErrorMessage = @"Exceeded max length (18 characters) for parameter ""ID""")]
public string ID { get; set; }
At this point, within my override, I need to dig into the HttpActionContent object "actionContext" to find the customized error messages.