AttributeRouting icon indicating copy to clipboard operation
AttributeRouting copied to clipboard

Routes with defaulted querystring constraints do not match when querystring parameter is missing

Open brantb opened this issue 12 years ago • 5 comments
trafficstars

Given an action method with a route defined as below, the URL /Index does not match any route.

public class HomeController : Controller
{
    [GET("Index?{page=1}")]
    public ActionResult Index(int page)
    {
        return View("Index", page);
    }
}

I expected that a URL like /Index would match this route and default the page routedata value to 1, but it does not.

When I actually specify a page querystring value (like /Index?page=4) it works as expected.

brantb avatar Sep 30 '13 15:09 brantb

I just looked at the specs and I don't have this case covered. :(

The fastest way for this to get fixed would be if you submitted a PR. I've been super busy with other things so it'll be a little bit before I can get to this and other issues, unfortunately.

In any case, thanks for reporting the issue!

mccalltd avatar Sep 30 '13 15:09 mccalltd

Thanks for the fast response! I'll take a look at the code and see if I can put together a PR.

As a temporary workaround, it seems to behave as expected if I change the route declaration and method signature to the following:

[GET("Index?{page=1?}")]
public ActionResult Index(int page = 1)
{
    return View("Index", page);
}

brantb avatar Sep 30 '13 15:09 brantb

Yeah. I suspected that adding a default value would work as a workaround. But it's gross to specify the default value twice!

And FYI: that ? at the end of page=1? should have no effect. But you can leave it in if it strikes you as pretty. :)

mccalltd avatar Sep 30 '13 15:09 mccalltd

Actually, for now I'd just do this for a workaround:

[GET("Index?{page?}")]
public ActionResult Index(int page = 1)

mccalltd avatar Sep 30 '13 15:09 mccalltd

And FYI: that ? at the end of page=1? should have no effect. But you can leave it in if it strikes you as pretty. :)

That's what I thought too, but when I take it out the route no longer matches. Weird, huh?

Your second suggestion works, though.

brantb avatar Sep 30 '13 15:09 brantb