c# - 使用属性路由时替换 Url.Link

标签 c# asp.net-web-api asp.net-web-api-routing attributerouting

我已将我的项目从 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/

相关文章:

c# - .net 如何从 MVC Controller 调用 web api 操作

c# - 如何检查我的电脑是否退出 sleep 模式

c# - MVC4 图片上传使用 Entity Framework 5 Code First

c# - 如何使用 servicestack 序列化程序将默认内容类型设置为 Json

javascript - 没有 'Access-Control-Allow-Origin' header - 相同域?

c# - 其他项目中的 Web Api Controller ,路由属性不起作用

c# - 将 Azure 设置为不预编译源代码

c# - 用于单元测试的 CaSTLe 类代理

c# - 转义 URL 中的反斜杠

c# - 多个可选参数路由