如何构造自定义WebApi路由,例如“ package / {packageName} / {controller}”,以路由到单独程序集中的Application Parts?

时间:2019-04-12 14:02:17

标签: c# asp.net-core asp.net-core-webapi asp.net-core-2.2

我们的应用程序将控制器加载到称为程序包的外部程序集中。我想创建一个使用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服务端点?

1 个答案:

答案 0 :(得分:2)

您可能正在与模板"package/{package}/{controller}/{id?}"发生路由冲突。

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

要获得所需的行为,您需要包括模板参数[Route("package/{package}/[controller]", Name = "Invoice")]以及方法/操作参数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