【问题标题】:Netcore how to remove endpoints/routes at runtimeNet Core 如何在运行时删除端点/路由
【发布时间】:2023-10-24 05:02:02
【问题描述】:

有没有办法删除net core web api项目中注册的路由?

所以我在net core web api项目中动态添加控制器,控制器类代码不是项目的一部分,而是在运行时动态加载、编译并添加到项目中

//code that compiles the c# class(controller) 
var compiledAssembly= CompileHelper.Compile(csharpCode)
using (var controllerAssemblyMs = new MemoryStream(compiledAssembly))
{
    var assemblyLoadContext = new SimpleAssemblyLoadContext();//inherits AssemblyLoadContext
    var dynamicControllers = new MvcAssemblyPart(controllerAssemblyMs);
    Services.AddControllersWithViews().ConfigureApplicationPartManager(apm => 
    apm.ApplicationParts.Add(dynamicControllers));
}

因此注册了任何新的端点/路由。

问题是因为每次编译代码时都注册了路由,如果我把Get动作改成Post动作,前后编译,endpoints最终会处于错误状态,

AmbiguousMatchException: The request matched multiple endpoints. Matches:

DynamicCodeProject.Controllers.DynamicallyAddedController.Post (string)
DynamicCodeProject.Controllers.DynamicallyAddedController.Get (string)

在这种情况下,我必须重新启动应用程序,

是否可以在运行时删除路由/端点,这样我就不必重新启动应用程序?

【问题讨论】:

    标签: asp.net-core .net-core routes asp.net-core-webapi endpoint


    【解决方案1】:

    我也有同样的问题。我的解决方案是从 apm.ApplicationParts 中删除以前的控制器

        var parts = _partManager.ApplicationParts.Where((x) => ((AssemblyPart)x).Assembly.GetName().Name == compiledAssembly.GetName().Name).ToList();
        foreach(var part in parts)
        {
            apm.ApplicationParts.Remove(part);
        }
    
        apm.AddApplicationPart(compiledAssembly);
    

    这项工作在 asp.net core 5.0 中

    【讨论】:

      最近更新 更多