Search code examples
c#dependency-injectionasp.net-web-api2asp.net-web-api-routing

Web Api 2 set route to ApiController method dynamically at runtime


I would like to set the route to a method within an ApiController dynamically. The below shows my TokenController:

public class TokenController : ApiController
{
    [Route("api/token/{grantType}")]
    [RequireHttps]
    public IHttpActionResult Post(string grantType)
    {}
}

I am thinking of using dependency injection as follows:

public class TokenController : ApiController
{
    public TokenController(ITokenService tokenService)
    {   
        //configure route "api/token/{grantType}" using tokenService?
    }

    [Route("api/token/{grantType}")]
    [RequireHttps]
    public IHttpActionResult Post(string grantType)
    {}
}

Or do I need to do this in App_Start using the HttpConfiguration object?

How would I do this?


Solution

  • Found my answer. I will configure the endpoint route with HttpConfiguration:

    public static class WebApiConfig
    {   
            public static void Register(HttpConfiguration config)
            {
                    config.Routes.MapHttpRoute(
                                name: "API TokenEndpoint",
                                routeTemplate: "services/newtoken/{grantType}",
                                defaults: new { controller = "Token" action="Post"},
                                constraints: null);
            }   
    }