11

I have a Web API project... I would like to respect the REST principles, so I should have just a GET method and just a POST method... I have to do a search, so i think this matches the GET method, because after the search I obtain the result and I show it in the page... If I do not find anything I must create the object... this action is a POST...

Now I have a problem... I must validate the filters of the search, because filters are a tax code and a alpha-numeric code (6 chars)... I have already done a client side validation. Now I should do a Server Side validation.

Untill now, we have used data annotation to validate the request, but this is a GET... so my method has this signature:

[HttpGet]
public IHttpActionResult GetActivationStatus(string taxCode, string requestCode)
{
    if (ModelState.IsValid)
    {
         ...
    }
}

But how can I validate my ModelState with Data Annotation?

Thank you

Simone
  • 149
  • 2
  • 9
  • possible duplicate http://stackoverflow.com/questions/2717250/is-it-possible-to-use-data-annotations-to-validate-parameters-passed-to-an-actio/2717270#2717270 – Mirza Danish Baig May 14 '15 at 07:53
  • yes, I think you are right... But the solution is really orrible... do you suggest another kind of validation? For example, "Fluent Validation" could help me? Or there is a way to pass a complex object with a GET ? – Simone May 14 '15 at 08:00
  • You're passing primitives. How do you expect to validate model state on them? You're either going to have to make a model and decorate it or do a custom action attribute that validates the action args. – Hardrada May 15 '15 at 03:14
  • I cannot do a model... It's a GET request – Simone May 15 '15 at 07:27

1 Answers1

11

Create your own model...

public class YourModel 
{
    [//DataAnnotation ...]
    public string taxCode { get; set; }
    [//DataAnnotation ...]
    public string requestCode { get; set; }
}

And change your signature of your server side controller:

[HttpGet]
public IHttpActionResult GetActivationStatus([FromUri] YourModel yourmodel)
{
    if (ModelState.IsValid)
    {
         ...
    }
}

If your client side code already worked you don't have to change it... Please, note that the properties of your Model are the same of the parameter you are passing now (string taxCode, string requestCode)... and they are case sensitive...

EDIT: I mean that you can call your controller in this way:

http://localhost/api/values/?taxCode=xxxx&requestCode=yyyy

Simone
  • 2,304
  • 6
  • 30
  • 79