我如何构建自定义 WebApi 路由,如 "package/{packageName}/{controller}" 以路由到单独程序集中的应用程序部件?

How can I construct custom WebApi routes like "package/{packageName}/{controller}" to route to Application Parts in a separate assembly?

我们的应用程序在我们称为包的外部程序集中加载控制器。我想创建一个路由,使用像 package/BillingPackage/Invoice 而不是 api/BillingPackage/Invoice 这样的 URL 路由到一个包。这是我所做的:

Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseEndpointRouting()
        .UseMvc(routes =>
    {
        routes.MapRoute(
            name: "package", 
            template: "package/{package}/{controller}/{id?}");
        routes.MapRoute("api", "api/{controller}/{action=Get}/{id?}");            
        routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
    });
    app.UseStaticFiles();
}

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    var source = new PackageAssemblySource(Configuration);
    var packageAssemblies = source.Load();
    var builder = new ContainerBuilder();
    builder.RegisterModule(new WebApiModule(packageAssemblies));

    services
        .AddMvc()
        .ConfigureApplicationPartManager(manager =>
        {
            // Add controllers and parts from package assemblies.
            foreach (var assembly in packageAssemblies)
            {
                manager.ApplicationParts.Add(new AssemblyPart(assembly));
            }
        });
        .AddControllersAsServices() // Now that AssemblyParts are loaded.
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);;

    builder.Populate(services);
    ApplicationContainer = builder.Build();

    return new AutofacServiceProvider(ApplicationContainer);
}

然后我这样定义一个控制器:

[Route("package/BillingPackage/[controller]", Name = "Invoice")]
public class InvoiceController : ControllerBase
{
    [HttpGet()]
    public ActionResult<Invoice> Get()
    {
        return new SampleInvoice();
    }
}

即便如此,package/BillingPackage/Invoice 仍会生成 404,而 api/BillingPackage/Invoice 不会。如何让我的 WebApi 为来自 package 而不是 api 的端点提供服务?

您可能遇到了与模板的路由冲突:"package/{package}/{controller}/{id?}"

如果在控制器上使用属性路由,则删除该基于约定的路由

要获得所需的行为,您需要包含一个模板参数 [Route("package/{package}/[controller]", Name = "Invoice")] 以及一个 method/action 参数 public ActionResult<Invoice> Get(string package),该参数将从 URL.

例如

[Route("package/{package}/[controller]", Name = "Invoice")]
public class InvoiceController : ControllerBase {

    //GET package/BillingPackage/Invoice
    [HttpGet()]
    public ActionResult<Invoice> Get(string package) {
        return new SampleInvoice();
    }
}

引用Routing to controller actions in ASP.NET Core