我已经将我的项目从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 });
发布于 2013-11-20 22:52:53
当您想要生成指向控制器/操作的属性路由的链接时,为什么要尝试使用传统的路由RouteDefaultApi
?
以下是如何将Url.Link与属性路由配合使用的示例用法:
[Route("api/values/{id}", Name = "GetValueById")]
public string GetSingle(int id)
Url.Link("GetValueById", new { id = 10 } );
https://stackoverflow.com/questions/20090428
复制相似问题