")] decorated on ApiController and in [Route] attribute I want t" /> ")] decorated on ApiController and in [Route] attribute I want t" /> ")] decorated on ApiController and in [Route] attribute I want t"/>

Using ApiExplorerSettings GroupName in Route in ASPNET Core

9.4k Views Asked by At

In ASP.NET Core - Web API project

Using [ApiExplorerSettings(GroupName = "<group-name>")] decorated on ApiController and in [Route] attribute I want to refer above GroupName property value.

Also note I do have [ApiVersion("<some-version>")] on same controller to classify further.

Here are some samples to explain:

Example 1:

Attribute on LeadController: [ApiVersion("1.0"), ApiExplorerSettings(GroupName = "sales"), [Route("api/{groupName}/v{version:apiVersion}/leads"]

Expected translated route format: /api/sales/v1/leads

Attribute on AccountsController: [ApiVersion("2.1"), ApiExplorerSettings(GroupName = "finance"), [Route("api/{groupName}/v{version:apiVersion}/accounts"]

Expected translated route format: /api/finance/v2.1/leads

In above {version:apiVersion} gives me ApiVersion value (I assume because that attribute has ToString set to version value). But when I try {groupName} or {grp:groupName} or {grp:ApiExplorerSettings.GroupName} - none of them works. How can access this group name in route attribute?

2

There are 2 best solutions below

1
mj1313 On

Do you have any special settings somewhere else, it works fine on my side.

LeadController:

[ApiVersion("1.0"), ApiExplorerSettings(GroupName = "sales"),Route("api/{groupName}/v{version:apiVersion}/leads")]
[ApiController]
public class LeadController : ControllerBase
{
    public string Get()
    {
        return "sales group";
    }
}

AccountsController:

[ApiVersion("2.1"), ApiExplorerSettings(GroupName = "finance"), Route("api/{groupName}/v{version:apiVersion}/accounts")]
[ApiController]
public class AccountsController : ControllerBase
{
    public string Get()
    {
        return "finance group";
    }
}

Result:

enter image description here

3
Chris Martinez On

ApiExplorerSettings.GroupName is only for the logical group name used in API descriptions. It is not used or evaluated in route templates. There is no way to make that work. That is why it never expands. It is possible to use a {groupName} route parameter, but it will be just that - a route parameter.

It's not entirely clear if you are trying to control grouping for the API Explorer or use a route parameter. Grouping is typically used by the API Explorer. API Versioning will assign or override the group name so that APIs are bucketized by their version. It is possible to change this behavior, but you'll need an API Explorer (via IApiDescriptionProvider) or OpenAPI/Swagger document generator extension to do it.