The Cookies Dog
The Cookies Dog

Reputation: 1940

ASP.NET Core route multiple optional parameters

In MVC 4 I had this custom route:

url+ "test/{id1}/{id2}/{id3}/{id4}/{id5}/{id6}/{id7}/{id8}/{id9}/{id10}/{id11}/{id12}",
                                                  new
                                                  {
                                                      controller = nameof(Test),
                                                      action = "Index",
                                                      id1 = UrlParameter.Optional,
                                                      id2 = UrlParameter.Optional,
                                                      id3 = UrlParameter.Optional,
                                                      id4 = UrlParameter.Optional,
                                                      id5 = UrlParameter.Optional,
                                                      id6 = UrlParameter.Optional,
                                                      id7 = UrlParameter.Optional,
                                                      id8 = UrlParameter.Optional,
                                                      id9 = UrlParameter.Optional,
                                                      id10 = UrlParameter.Optional,
                                                      id11 = UrlParameter.Optional,
                                                      id12 = UrlParameter.Optional
                                                  }

This was going to a single method in TestController. However, I can't seem to get this working in Core.

If I have

"Test Controller", "/test/{action}/{id1?}/{id2?}/{id3?}/{id4?}/{id5?}/{id6?}/", new { Controller = "Test", Action = "Index" }

In controller:

[HttpGet]    
public IActionResult Index(string id1, string id2, string id3, string id4, string id5, string id6)
    {
        return Ok("hello world");
    }

Then it only works if I specify the ids as query parameters. I need the slashes in the URLs.

Route attributes work, but the URL is dynamic and I don't think that's working well together.

How would I need to build the route here to get this to work?

Upvotes: 1

Views: 455

Answers (1)

Serge
Serge

Reputation: 43880

it is better to use attribute routing

[HttpGet("~/test/index/{id1?}/{id2?}/{id3?}/{id4?}/{id5?}/{id6?}")]
public IActionResult Index(string id1, string id2, string id3, string id4, string id5, string id6)
    {
        return Ok("hello world");
    }

Upvotes: 1

Related Questions