Tom Vaidyan
Tom Vaidyan

Reputation: 400

How can I setup attribute based routing in ASP.NET Core 3.0

In my startup.cs class I have:

app.UseRouting();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

My controller currently looks like so:

[Microsoft.AspNetCore.Components.Route("api/my-test")]
public class MyTestController : ControllerBase
{
    [HttpGet]
    [Route("{confirmationCode}")]
    public async Task<IActionResult> Get(string confirmationCode)
    {
        return Ok($"The confirmation code is: {confirmationCode}");
    }
}

How can I call the Get action on my MyTestController and get access to the confirmation code that was passed in as part of the URL from a route URL that looks like this: /api/my-test/abc123

Upvotes: 0

Views: 337

Answers (1)

Tom Vaidyan
Tom Vaidyan

Reputation: 400

Figured out the solution on my own after a few more attempts:

[Route("api/my-test")] // <-- this Route is from Microsoft.AspNetCore.Mvc.RouteAttribute
public class MyTestController : ControllerBase
{
    // GET api/my-test/abc123
    [HttpGet("{confirmationCode}")] // <-- instead of Route, you tack on the rest of your route pattern into the HttpGet attribute (or other verbs depending on your code)
    public async Task<IActionResult> Get(string confirmationCode)
    {
        return Ok($"The confirmation code is: {confirmationCode}");
    }
}

Here are the two changes / differences:

  1. The "Route" element in my non-working code was from "Microsoft.AspNetCore.Components". The correct namespace is "Microsoft.AspNetCore.Mvc.RouteAttribute".
  2. Instead of using "Route" at the Action Method level, add the rest of your route pattern to the HTTP verb decoration. In my example above, I added it to the HttpGet decorator that I had on the method.

Upvotes: 2

Related Questions