Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net webapi: how to pass optional parameters?

I am using the new asp.net web api and would like to pass optional parameters. Is it correct that one needs to populate an attribute so it allows one to pass params using the ? symbol?

Before this was done with with uri templates, I believe.

Does anyone have an example?

I am currently passing the id in the url which arrives in my controller as int. But I need to pass some dates.

like image 782
Martin Avatar asked May 31 '12 08:05

Martin


2 Answers

You can make a parameter optional by using a nullable type:

public class OptionalParamsController : ApiController
{
    // GET /api/optionalparams?id=5&optionalDateTime=2012-05-31
    public string Get(int id, DateTime? optionalDateTime)
    {
        return optionalDateTime.HasValue ? optionalDateTime.Value.ToLongDateString() : "No dateTime provided";
    }
}
like image 147
Ian Gilroy Avatar answered Nov 02 '22 23:11

Ian Gilroy


In addition to the previous answer provided by Ian, which is correct, you can also provide default values which I feel is a cleaner option which avoids having to check whether something was passed or not. Just another option.

public class OptionalParamsController : ApiController
{
    // GET /api/optionalparams?id=5&optionalDateTime=2012-05-31
    public string Get(int id, DateTime optionalDateTime = DateTime.UtcNow.Date)
    {...}
}
like image 26
AlexGad Avatar answered Nov 03 '22 00:11

AlexGad