Search code examples
c#asp.netasp.net-web-apiasp.net-mvc-routingowin

C# .net OWIN - starting a route for a WebAPI with a Wildcard dynamic URL


I have a WebApi hosted in OWIN and I was wondering if it was possible to have the beginning of the URL a "wildcard", so for example if I have a WebAPI named "GetUsers", a person accessing my WebAPI would be able to type:

http://localhost/blah-blah-blah/api/GetUsers

http://localhost/api/GetUsers

http://localhost/ABC/api/GetUsers

and all routes would take him to GetUsers. Is this possible? I tried stuff like adding [Route("{*uri}/api/GetUsers")] to the function but it doesn't seem to work, tried the same in WebAPIConfig ->

config.Routes.MapHttpRoute(
    name: "ControllerAndAction", 
    routeTemplate: "{*uri}/api/{controller}/{action}"
); 

but that didn't work as well.

Is there any way to create a WebAPI with a "wildcard starting URL", or is it impossible?


Solution

  • Do not use the * in your proposed route template. It will cause conflicts. {prefix}/api/{controller}/{action} should work for your 1st and 3rd option. Optional placeholders are not allowed in the middle of route templates so you would have to register the api/{controller}/{action} separately.

    config.Routes.MapHttpRoute(
        name: "PrefixedControllerAndAction", 
        routeTemplate: "{prefix}/api/{controller}/{action}"
    ); 
    
    config.Routes.MapHttpRoute(
        name: "ControllerAndAction", 
        routeTemplate: "api/{controller}/{action}"
    );