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

问题描述 投票:1回答:1

我们的app将控制器加载到我们称之为包的外部组件我想创建一个使用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服务端点?

c# asp.net-core asp.net-core-webapi asp.net-core-2.2
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.