7

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.

1
  • Could you clarify a bit more what your scenario is? What action method signature do you expect? What routing changes have you made? Some information about Web API routing basics is available here: asp.net/web-api/overview/web-api-routing-and-actions/… Commented May 31, 2012 at 22:10

2 Answers 2

6

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";
    }
}
Sign up to request clarification or add additional context in comments.

Comments

3

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)
    {...}
}

3 Comments

Optional parameters must be compile-time constant, DateTime is NEVER a compile-time constant.
Oops, yes you are correct. A datetime can not be provided as an optional parameter and I should not have used that as an example. However, other datatypes can be used in this way.
In my current project, if I don't provide a default value, the route is not resolved, returning a 404 (Not found) HTTP error. The method signature must be void MyAction(long id, long? value1=-1, long? value2=-1) ... If I do not provide the default values it fails if not passed on the query string!

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.