C# web api中的路由属性忽略uri的一部分
我有一个控制器C# web api中的路由属性忽略uri的一部分,c#,asp.net-web-api,asp.net-web-api-routing,C#,Asp.net Web Api,Asp.net Web Api Routing,我有一个控制器 public class SimulatorController : ApiController { private SimulatorService _simulatorService; public SimulatorController() { _simulatorService = new SimulatorService(); } [HttpGet] [Route("spiceusers")]
public class SimulatorController : ApiController
{
private SimulatorService _simulatorService;
public SimulatorController()
{
_simulatorService = new SimulatorService();
}
[HttpGet]
[Route("spiceusers")]
public async Task<IHttpActionResult> GetConsumerProductsAsync()
{
var consumerProductsList = await _simulatorService.GetConsumerProductsAsync();
return Ok(consumerProductsList);
}
}
是否忽略uri的其他部分?您可以使用catch all route参数,如
{*segment}
来捕获URL路径的其余部分
这里的假设是属性路由已经启用
public static class WebApiConfig {
public static void Register(HttpConfiguration config) {
// Web API routes
config.MapHttpAttributeRoutes();
// Other Web API configuration not shown.
}
}
发布的示例中的URL可以通过使用catch all route参数与操作匹配,该参数将捕获与模板匹配的URL路径的剩余部分
//GET spiceusers/{anything here}
[HttpGet]
[Route("~/spiceusers/{*url}")]
public async Task<IHttpActionResult> GetConsumerProductsAsync() { ... }
//获取用户//{此处有任何内容}
[HttpGet]
[路由(“~/spiceusers/{*url}”)]
公共异步任务GetConsumerProductsAsync(){…}
现在,对/spiceusers
的任何调用都将按照预期映射到上述操作
请注意,这还包括spiceusers
模板下的所有子调用,前提是这是预期的
还请注意,如果此web api与默认MVC一起使用,则路径my与默认路由冲突。但考虑到WEPAPI路由往往在MVC路由之前注册,这可能不是什么大问题