I know that you can use Validation attributes on a model to validate it like so:
public class CommunicationQuery
{
[RegularExpression("[0-9]{0,10}", ErrorMessage = "Please enter a valid policy number")]
public string PolicyId { get; set; }
[RegularExpression("[0-9]{0,10}", ErrorMessage = "Please enter a valid member number")]
public string MemberId { get; set; }
}
public IEnumerable<Communication> Get([FromUri]CommunicationQuery documentQuery)
{
}
But is it possible to validate a single string using validation attributes such as this?
public async Task<HttpResponseMessage> Get([RegularExpression("[0-9]{0,10}")]string id)
{
}
This didn't seem to work. The only ways I've been able to do this was to either create a wrapper object and use [FromUri]
, use a custom ActionFilterAttribute
on the action itself or to manually validate the parameter in the controller action using a regular expression.
If you're using Attribute Routing to manage your paths coming into your controllers, you can always do something like this:
[Route("{Id:regex([0-9]{0,10})}")]
public async Task<HttpResponseMessage> Get(string id)
{
}
There are various route contraints, as documented on the Attribute Routing overview documentation.
It does raise the question as to why you're accepting a numeric string of length 10 as your id. you'll have to be careful when parsing it into an int that it doesn't exceed 2,147,483,647
, as that's the maximum size for a default integer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With