简体   繁体   English

web api中的路由属性忽略部分uri

[英]Routing attribute in web api ignore part of uri

I have a controller我有一个控制器

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);
    }

} 

And i have uri我有 uri

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

I need that my method should processed我需要处理我的方法

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

and ignore othrer part of uri?并忽略uri的其他部分?

You can use the catch-all route parameters like {*segment} to capture the remaining portion of the URL path.您可以使用诸如{*segment}类的包罗万象的路由参数来捕获 URL 路径的剩余部分。

The assumption here is that attribute routing is already enabled.这里的假设是属性路由已经启用。

public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {
        // Web API routes
        config.MapHttpAttributeRoutes();

        // Other Web API configuration not shown.
    }
}

The URL in the example posted can be matched to the action by using the catch-all route parameter which will capture the remaining portion of the URL path that matched the template发布示例中的 URL 可以通过使用 catch-all 路由参数与操作匹配,该参数将捕获与模板匹配的 URL 路径的剩余部分

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

Now any calls to /spiceusers will map to the above action as intended.现在,对/spiceusers任何调用都/spiceusers映射到上述操作。

Note that this also includes all sub calls below the spiceusers template, provided that is what was intended.请注意,这还包括spiceusers模板下的所有子调用,前提是这是预期的。

Note also that if this web api is being used along with the default MVC that the path my clash with the default routing.另请注意,如果此 Web api 与默认 MVC 一起使用,则路径与默认路由发生冲突。 But given that wep api routes tend to be registered before MVC routes it may not be that much of an issue.但是考虑到 wep api 路由往往在 MVC 路由之前注册,这可能不是什么大问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM