2

Does WebAPI can handle ValidationAttribute on action parameter?

For instance:

public class SampleController : ApiController
{
   public string Get([RegularExpression("sampleExpression")]string id)
   {
      return "result";
   }
}

In this sample WebAPI doesn't invoke any methods of RegularExpressionAttribute (or any other data annotation attribute) to validate input parameter. But in case if we passing an object as parameter, for instance a class then WebAPI can validate properties.

Is it a bug? Or I'm doing something wrong?

UPD: It's an open issue: http://aspnetwebstack.codeplex.com/workitem/24?PendingVoteId=24

Does anyone can suggest a workaround?

2 Answers 2

1

This is a genuine question, I'm curious why not just do something like :

public class SampleController : ApiController
{
   public string Get(string id)
   {
      RegularExpressionHelper.ValidateWith("sampleExpression",id);

      return "result";
   }
}

To me this seems to be equivalently concise. It is obvious when the validation occurs. I can safely assume that if the validation fails then an exception will be thrown. I can easily add additional validation and be confident of the order in which they occur.

Regarding the attribute method, I don't know if the validation is used as part of the route matching, I have no idea what happens if it fails. I don't know what filters run before or after the validation. I'm sure if I knew MVC better I would know the answer to these questions, but I don't see the advantage of using an attribute that makes my code's behaviour dependent on some framework controlled infrastructure.

Am I missing some significant benefit?

Sign up to request clarification or add additional context in comments.

Comments

0

I had the same doubt. My workaround consists in creating a class just for encapsulating the parameter, so I can decorate it with the validation attribute I want. I could use the workaround proposed by Darrel in his answer, but I have a filter that checks if ModelState.IsValid before entering the action, so I need to validate before the action gets executed.

[ModelBinder]
public class Item
{
    [RegularExpression("sampleExpression")]
    public string Id { get; set; }
}

The class must be annotated with [ModelBinder], otherwise the parameter binding mechanism will try to extract the id field from the body of the request. Read this article for more info.

Also, note that Id is now in PascalCase instead of camelCase. Read this article to understand how the conversion is made.

The action signature is:

public string Get(Item item)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.