aspnetcore: ControllerBase Route attribute is ignored in dynamically loaded AssemblyParts

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

The Route attribute of ControllerBase is ignored when an AssemblyPart is dynamically loaded (built using a separate C# project that uses nuget Microsoft.AspNetCore.Mvc.Core.dll).

I am loading a dynamic library (Assembly.Load) and then I add AsseblyParts to the IServiceCollection.AddControllers. Controller - in the other library (not referenced by the main Web project):

    [ApiController]
    [Route("api/[controller]")]
    [AllowAnonymous]
    public class AsopController : ControllerBase
    {
        public AsopController()
        {
        }

        [HttpGet()]
        public IActionResult Get()
        {
            return Ok(new { text = "OK" });
        }
    }

Startup.cs - ConfigureDevelopmentServices(IServiceCollection serviceCollection)

var pluginsPath = Path.Combine(AppContext.BaseDirectory, @".\Plugins");
string[] pluginPaths = Directory.GetFiles(pluginsPath, "*.Plugin.dll", SearchOption.AllDirectories);

            foreach (var pluginPath in pluginPaths)
            {
                Assembly pluginAssembly = pluginPath.LoadAssembly(); // this is just Assembly.Load

                IMvcBuilder mvcBuilder = serviceCollection.AddControllers();
                mvcBuilder.ConfigureApplicationPartManager(pm =>
                {
                    pm.ApplicationParts.Add(new AssemblyPart(pluginAssembly));
                });
            }

In ConfigureDevelopment(IApplicationBuilder app):

 app.UseRouting();
...
 app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
            });

The endpoints are now populated with the MVC style routes: controller=Home/action=Index/… so, the initial route is ignored.

Expected Behavior

The request route should be found according to the definition in controller Route attribute.

Steps To Reproduce

See code above.

Exceptions (if any)

No response

.NET Version

6

Anything else?

No response

About this issue

  • Original URL
  • State: closed
  • Created a year ago
  • Comments: 19 (12 by maintainers)

Most upvoted comments