Web Api 2在运行时动态设置到ApiController方法的路由

问题描述 投票:0回答:1

我想动态地设置ApiController中的方法的路由。下面显示了我的TokenController:

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

我正在考虑使用依赖注入如下:

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

或者我是否需要使用HttpConfiguration对象在App_Start中执行此操作?

我该怎么做?

c# dependency-injection asp.net-web-api2 asp.net-web-api-routing
1个回答
1
投票

找到我的答案。我将使用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);
        }   
}
© www.soinside.com 2019 - 2024. All rights reserved.