我已将我的项目从 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 });
最佳答案
当您想生成指向 Controller /操作的属性路由的链接时,为什么要尝试使用传统路由 RouteDefaultApi
?
以下是您需要如何将 Url.Link 与属性路由一起使用的示例用法:
[Route("api/values/{id}", Name = "GetValueById")]
public string GetSingle(int id)
Url.Link("GetValueById", new { id = 10 } );
关于c# - 使用属性路由时替换 Url.Link,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20090428/