1
votes

Shouldn't these two approaches effectively achieve the same thing?

Approach #1 aka 'conventional routing'

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
        endpoints.MapControllerRoute(name: "api", pattern: "api/[controller]");
        endpoints.MapRazorPages();
    });

Now, disable/comment the line above that calls MapControllerRoute, then do the following in the controller, adding the attibute based routing at the top.

approach #2, aka 'attribute based routing'

    [ApiController]
    [Route("api/Box")]
    public class BoxController : BaseController
    {
            [HttpGet("{customer}")]
            public IActionResult Get(string customer, string size, string color)
            {
                //string customer = "test";

                string retval = "test"; //...do stuff here

                return Ok(retval);
            }
}

With approach#1, the following route resolved
localhost:5511/box/abc?size=val1&color=val2
but not
localhost:5511/api/box/abc?size=val1&color=val2

using attribute-based routing, the route I needed was resolved
localhost:5511/api/box/abc?size=val1&color=val2

1

1 Answers

0
votes

They are the same, there are a few details you missed

  1. Replace the square brackets [] with curly ones {} in the route pattern, as this way the framework evaluates route patterns:

    endpoints.MapControllerRoute(name: "api", pattern: "api/{controller}")

  2. Then remove [HttpGet("{customer}")] from above the action

  3. Add to route pattern the action:

    endpoints.MapControllerRoute(name: "api", pattern: "api/{controller}/{action}")

Voila, now the endpoint looks just right!