Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate GET url parameters through ModelState with data annotation

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

like image 266
Simone Avatar asked May 14 '15 07:05

Simone


People also ask

How do you validate data annotations?

DataAnnotations namespace includes the following validator attributes: Range – Enables you to validate whether the value of a property falls between a specified range of values. RegularExpression – Enables you to validate whether the value of a property matches a specified regular expression pattern.

How do I validate parameters in Web API?

You can use action filters for logging, authentication, output caching, Validations or other tasks. You implement an action filter as an attribute, which is inherited from the ActionFilterAttribute class. You override the OnActionExecuting method, if you want your logic to run before the Action Method.

Can we do validation in MVC using data annotations?

In Asp.net MVC, we can easily apply validation to web application by using Data Annotation attribute classes to model class. Data Annotation attribute classes are present in System.


1 Answers

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

like image 98
Ciccio Avatar answered Oct 18 '22 12:10

Ciccio