Skip to content

Conversation

mdubbelv
Copy link

Prerequisites

This PR fixes this issue:
#20143

It adds the possibility to add Controllers to a Swagger document at runtime. For example by using a IApplicationModelConvention
That is achieved by not checking MethodInfo and instead checking ActionDescriptor.EndpointMetaData when trying to find a MapToApiAttribute on a Controller when filtering out documents using SwaggerGenOptions.DocInclusionPredicate.

Description

Test by:

  1. Add custom Swagger document
  2. Add Controller with MapToApiAttribute matching the custom Swagger document
    See more: https://docs.umbraco.com/umbraco-cms/reference/api-versioning-and-openapi#adding-your-own-swagger-documents

Copy link

Hi there @mdubbelv, thank you for this contribution! 👍

While we wait for one of the Core Collaborators team to have a look at your work, we wanted to let you know about that we have a checklist for some of the things we will consider during review:

  • It's clear what problem this is solving, there's a connected issue or a description of what the changes do and how to test them
  • The automated tests all pass (see "Checks" tab on this PR)
  • The level of security for this contribution is the same or improved
  • The level of performance for this contribution is the same or improved
  • Avoids creating breaking changes; note that behavioral changes might also be perceived as breaking
  • If this is a new feature, Umbraco HQ provided guidance on the implementation beforehand
  • 💡 The contribution looks original and the contributor is presumably allowed to share it

Don't worry if you got something wrong. We like to think of a pull request as the start of a conversation, we're happy to provide guidance on improving your contribution.

If you realize that you might want to make some changes then you can do that by adding new commits to the branch you created for this work and pushing new commits. They should then automatically show up as updates to this pull request.

Thanks, from your friendly Umbraco GitHub bot 🤖 🙂

@mdubbelv mdubbelv marked this pull request as ready for review September 16, 2025 07:09
Copy link
Contributor

@AndyButland AndyButland left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for raising this issue @mdubbelv-consid and providing a solution. I've tested out, and it looks to work as expected.

Let me just relay my testing steps so you or anyone else looking at this can verify they are valid.

  1. Created a new, standalone management API endpoint:
using Asp.Versioning;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Umbraco.Cms.Api.Common.Attributes;
using Umbraco.Cms.Api.Common.Filters;
using Umbraco.Cms.Api.Common.ViewModels.Pagination;
using Umbraco.Cms.Api.Management.DependencyInjection;
using Umbraco.Cms.Api.Management.Filters;
using Umbraco.Cms.Api.Management.Routing;
using Umbraco.Cms.Api.Management.ViewModels.Culture;
using Umbraco.Cms.Core;
using Umbraco.Cms.Web.Common.Authorization;
using Umbraco.Cms.Web.Common.Filters;

namespace Umbraco.Cms.Api.Management.Controllers.Culture;

[ApiVersion("1.0")]
[VersionedApiBackOfficeRoute("andy-testing")]
[ApiExplorerSettings(GroupName = "Andy Testing")]
[ApiController]
[Authorize(Policy = AuthorizationPolicies.BackOfficeAccess)]
[MapToApi(ManagementApiConfiguration.ApiName)]
[JsonOptionsName(Constants.JsonOptionsNames.BackOffice)]
[AppendEventMessages]
[DisableBrowserCache]
public class TestController : Controller
{
    [HttpGet]
    [MapToApiVersion("1.0")]
    [ProducesResponseType(typeof(PagedViewModel<CultureReponseModel>), StatusCodes.Status200OK)]
    public Task<string> Get(CancellationToken cancellationToken)
    {
        return Task.FromResult("Hello");
    }
}
  1. Verified that it appeared on the Swagger UI at: /umbraco/swagger/index.html?urls.primaryName=Umbraco+Management+API

  2. Commented out [MapToApi(ManagementApiConfiguration.ApiName)] and verified that it no longer appeared.

  3. Add the following class to the solution:

using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Umbraco.Cms.Api.Common.Attributes;
using Umbraco.Cms.Api.Management.Controllers.Culture;

namespace Umbraco.Cms.Api.Management;

public sealed class MapToApiConvention(string apiName) : IApplicationModelConvention
{
    public void Apply(ApplicationModel app)
    {
        SetMapToApiName(app, apiName);
    }

    private static void SetMapToApiName(ApplicationModel app, string apiName)
    {
        foreach (var controller in app.Controllers)
        {
            if (!typeof(TestController).IsAssignableFrom(controller.ControllerType))
                continue;

            if (controller.Attributes.OfType<MapToApiAttribute>().Any())
                continue;

            var attribute = new MapToApiAttribute(apiName);

            foreach (var action in controller.Actions)
            {
                foreach (var selector in action.Selectors)
                {
                    selector.EndpointMetadata.Add(attribute);
                }
            }
        }
    }
}
  1. Registered it in my start-up project with:
  public void Compose(IUmbracoBuilder builder) => builder.Services
      .AddMvc(options =>
      {
          options.Conventions.Add(new MapToApiConvention("management"));
      });
  1. Verified that with the current code in main the endpoint still does not appear on the Swagger UI documentation.
  2. Switched to the code provided by this PR, rebuilt, and now the endpoint does appear on the Swagger UI documentation.

So I think this is all good to go once the raised comments are resolved.

I'll also ask - but not insist as I don't know how difficult it would be - but wonder if it's possible to add some form of automated testing for this? I.e. verify that ConfigureUmbracoSwaggerGenOptions will now correctly handle both compile and runtime attributes. That would be nice as a check against future regressions and also help document the behaviour.

@AndyButland AndyButland changed the title Use EndpointMetadata to check for MapToApiAttribute at runtime to include Controller in Swagger document APIs: Use EndpointMetadata to check for MapToApiAttribute at runtime to include Controller in Swagger document Sep 19, 2025
@mdubbelv
Copy link
Author

mdubbelv commented Sep 29, 2025

Thanks for raising this issue @mdubbelv-consid and providing a solution. I've tested out, and it looks to work as expected.

Let me just relay my testing steps so you or anyone else looking at this can verify they are valid.

  1. Created a new, standalone management API endpoint:
using Asp.Versioning;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Umbraco.Cms.Api.Common.Attributes;
using Umbraco.Cms.Api.Common.Filters;
using Umbraco.Cms.Api.Common.ViewModels.Pagination;
using Umbraco.Cms.Api.Management.DependencyInjection;
using Umbraco.Cms.Api.Management.Filters;
using Umbraco.Cms.Api.Management.Routing;
using Umbraco.Cms.Api.Management.ViewModels.Culture;
using Umbraco.Cms.Core;
using Umbraco.Cms.Web.Common.Authorization;
using Umbraco.Cms.Web.Common.Filters;

namespace Umbraco.Cms.Api.Management.Controllers.Culture;

[ApiVersion("1.0")]
[VersionedApiBackOfficeRoute("andy-testing")]
[ApiExplorerSettings(GroupName = "Andy Testing")]
[ApiController]
[Authorize(Policy = AuthorizationPolicies.BackOfficeAccess)]
[MapToApi(ManagementApiConfiguration.ApiName)]
[JsonOptionsName(Constants.JsonOptionsNames.BackOffice)]
[AppendEventMessages]
[DisableBrowserCache]
public class TestController : Controller
{
    [HttpGet]
    [MapToApiVersion("1.0")]
    [ProducesResponseType(typeof(PagedViewModel<CultureReponseModel>), StatusCodes.Status200OK)]
    public Task<string> Get(CancellationToken cancellationToken)
    {
        return Task.FromResult("Hello");
    }
}
  1. Verified that it appeared on the Swagger UI at: /umbraco/swagger/index.html?urls.primaryName=Umbraco+Management+API
  2. Commented out [MapToApi(ManagementApiConfiguration.ApiName)] and verified that it no longer appeared.
  3. Add the following class to the solution:
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Umbraco.Cms.Api.Common.Attributes;
using Umbraco.Cms.Api.Management.Controllers.Culture;

namespace Umbraco.Cms.Api.Management;

public sealed class MapToApiConvention(string apiName) : IApplicationModelConvention
{
    public void Apply(ApplicationModel app)
    {
        SetMapToApiName(app, apiName);
    }

    private static void SetMapToApiName(ApplicationModel app, string apiName)
    {
        foreach (var controller in app.Controllers)
        {
            if (!typeof(TestController).IsAssignableFrom(controller.ControllerType))
                continue;

            if (controller.Attributes.OfType<MapToApiAttribute>().Any())
                continue;

            var attribute = new MapToApiAttribute(apiName);

            foreach (var action in controller.Actions)
            {
                foreach (var selector in action.Selectors)
                {
                    selector.EndpointMetadata.Add(attribute);
                }
            }
        }
    }
}
  1. Registered it in my start-up project with:
  public void Compose(IUmbracoBuilder builder) => builder.Services
      .AddMvc(options =>
      {
          options.Conventions.Add(new MapToApiConvention("management"));
      });
  1. Verified that with the current code in main the endpoint still does not appear on the Swagger UI documentation.
  2. Switched to the code provided by this PR, rebuilt, and now the endpoint does appear on the Swagger UI documentation.

So I think this is all good to go once the raised comments are resolved.

I'll also ask - but not insist as I don't know how difficult it would be - but wonder if it's possible to add some form of automated testing for this? I.e. verify that ConfigureUmbracoSwaggerGenOptions will now correctly handle both compile and runtime attributes. That would be nice as a check against future regressions and also help document the behaviour.

Hi @AndyButland and thank you for the review and testing.
I will find some time to see if there are any appropriate ways to automatically test the changes.

Might be hard to test the Swagger generation. I might be able to create a test that checks the presence of the MapToApiAttribute in one Controller with statically added MapToApiAttribute and in one Controller with MapToApiAttribute in runtime.

@AndyButland
Copy link
Contributor

AndyButland commented Sep 29, 2025

I might be able to create a test that checks the presence of the MapToApiAttribute in one Controller with statically added MapToApiAttribute and in one Controller with MapToApiAttribute in runtime.

Yes, that's what I was thinking. So a test of HasMapToApiAttribute that verifies it's functionality for the two scenarios where a MapToApiAttribute can be added. As I say though, if it proves particular challenging, it's not a requirement to merge the PR. But thanks for giving it a go.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants