17

我已将我的项目从 webapi 升级到 webapi2,现在正在使用属性路由。我有一个方法,我使用 Url helper 来获取 url。这是替换 Url 助手的最佳方法(因为这不适用于属性)。

我的旧用法示例代码:

protected Uri GetLocationUri(object route, string routeName = WebApiConfig.RouteDefaultApi)
{
    string uri = Url.Link(routeName, route);
    return new Uri(uri);
}

路线配置:

public static void Register(HttpConfiguration config)
{
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: RouteDefaultApi,
        routeTemplate: "{controller}/{id}/{action}",
        defaults: new { id = RouteParameter.Optional, action = "Default" }
    );           
}

用法:

Uri myUrl = GetLocationUri(route: new { action = "images", id = eventId });
4

1 回答 1

41

RouteDefaultApi当您想生成指向控制器/动作的属性路由的链接时,为什么要尝试使用传统路由?

以下是如何将 Url.Link 与属性路由一起使用的示例用法:

[Route("api/values/{id}", Name = "GetValueById")]
public string GetSingle(int id)

Url.Link("GetValueById", new { id = 10 } );
于 2013-11-20T14:52:52.933 回答