0

I'm trying to make an action with 2 parameters, 1 is optional I'm trying with

 [HttpGet, Route("movies/date/{dateMin}&{dateMax}")]

But it's not working. 'dateMax' is optional parameter, and when it's not given it should be the same value as dateMin Already tried with

 [HttpGet, Route("movies/date/{dateMin}&{dateMax?}")]

But it's not working either. I dont want to have something like

{dateMin}/{dateMax}

Is there other possibility to do that?

2 Answers 2

1

You need to segregate the route parameters in your route using a slash and not using the query string notation (&).

[HttpGet, Route("movies/date/{dateMin}/{dateMax?}")]
public IHttpActionResult MoviesDate(DateTime dateMin, DateTime? dateMax){
}

There is no need to change the route config if you use RoutAttribute

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much :) Also i have a 2nd question. I have "[HttpGet, Route("movies/{movieId:int?}/xx")]" I want to make it work with "movies/2/xx" - getting xx only for movieId=2 and "movies/xx" - getting all xx Is there a possibility to do that?
@Pawel - no. If you use positional parameters the order is critical and optional parameters should be placed before required parameters. Your best bet would be to use a query string instead and binding them by name instead of making them positional based. To do that omit them from the route template completely, keep them as parameter in the method making them nullable (adding ? for value types) and assigning a default value. Then they are optional and you can use a query string parameter to include a value.
1

You should be doing that in your RouteConfig.cs

 routes.MapRoute(
        name: "Movies",
        url: "{controller}/{action}/{dateMin}/{dateMax}",
        defaults: new { controller = "movies", action = "date", dateMax= UrlParameter.Optional }
        );

Your Route should be like this

"{controller}/{action}/{dateMin}/{dateMax}"

Comments