Skip to main content

Accept only int value for ASP.NET Web API action method parameter

In this short post, find solution to how to accept only int value for ASP.NET Web API action method parameter. Below is an example of Web API action method which accepts an int type parameter. And it returns the same value as response.

// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
    return id.ToString();
}

So when you hit http://localhost:59845/api/values/5, you get “5” returned in response. And when you hit http://localhost:59845/api/values/abc, then you get “0” as returned. But what if, you want to accept only integer value and if input parameter is not “int” then return a 404 error.

With attribute routing, you can also define the data type constraint for parameter. So updated action method is,

// GET api/values/5
[HttpGet("{id:int}")]
public string Get(int id)
{
    return id.ToString();
}

So now when you hit http://localhost:59845/api/values/abc, then you shall get 404 error. You can use any data type for route constraint as per your requirement.

Hope you like it. Stay tuned for more!.

PS: If you found this content valuable and want to return the favour, then Buy Me A Coffee

One thought to “Accept only int value for ASP.NET Web API action method parameter”

Leave a Reply

Your email address will not be published. Required fields are marked *