我已经将项目从webapi升级到了webapi2,现在正在使用属性路由。我有一种使用Url助手获取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 });

最佳答案

当您想生成指向 Controller / Action 的属性路由的链接时,为什么要尝试使用常规路由RouteDefaultApi

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

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

Url.Link("GetValueById", new { id = 10 } );

10-01 23:44
查看更多