Search code examples
c#asp.net-web-apiasp.net-web-api-routing

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

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?


Solution

  • You can use the catch-all route parameters like {*segment} to capture the remaining portion of the URL path.

    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

    //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.

    Note that this also includes all sub calls below the spiceusers template, provided that is what was intended.

    Note also that if this web api is being used along with the default MVC that the path my clash with the default routing. But given that wep api routes tend to be registered before MVC routes it may not be that much of an issue.