我们的app将控制器加载到我们称之为包的外部组件我想创建一个使用package/BillingPackage/Invoice
而不是api/BillingPackage/Invoice
之类的URL路由到包的路由。这是我做的:
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")]
以及方法/操作参数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();
}
}