【问题标题】:Routing attribute in web api ignore part of uriweb api中的路由属性忽略uri的一部分
【发布时间】:2017-06-04 11:04:46
【问题描述】:

我有一个控制器

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

http://comm-rpp-emulator.com/spiceusers/9656796/devicesfuse?includeComponents=true&amp;groupByParentDevice=true&amp;includeChildren=true&amp;limit=50&amp;page=1

我需要处理我的方法

http://comm-rpp-emulator.com/spiceusers

忽略uri的其他部分?

【问题讨论】:

    标签: c# asp.net-web-api asp.net-web-api-routing


    【解决方案1】:

    您可以使用诸如{*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 路由参数与操作匹配,该参数将捕获与模板匹配的 URL 路径的剩余部分

    //GET spiceusers/{anything here}
    [HttpGet]
    [Route("~/spiceusers/{*url}")]
    public async Task<IHttpActionResult> GetConsumerProductsAsync() { ... }
    

    现在对/spiceusers 的任何调用都将按预期映射到上述操作。

    请注意,这还包括spiceusers 模板下的所有子调用,前提是这是预期的。

    还请注意,如果此 Web api 与默认 MVC 一起使用,则路径与默认路由发生冲突。但鉴于 wep api 路由往往在 MVC 路由之前注册,这可能不是什么大问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-16
      • 1970-01-01
      • 2017-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多