【问题标题】:WebApi's UrlHelper.Link() does not escape forward slashes (/)WebApi 的 UrlHelper.Link() 不会转义正斜杠 (/)
【发布时间】:2015-10-13 02:34:04
【问题描述】:

UrlHelper.Link() 没有转义 routeValues 中存在的正斜杠,并且生成的 URL 与 Link() 生成 URL 所依据的路由不匹配,这让我有点困惑。这是我遇到的具体示例:

我定义了以下命名路由模板:

Presentation/{presentationID}/Transition/{SlideIndex}/{playStart}

在构建响应时,我还有以下代码来生成 URL:

this.Url.Link(RouteNameConstants.PresentationTransition,
    new {
        action = ActionNameConstants.PresentationController.Transition,
        presentationId = presentation.PresentationId,  // value: ab/cdefg
        slideIndex = slideIndex,  // value: 1
        playStart = DateTime.UtcNow.AddMilliseconds(-offsetInMilliseconds).Ticks
    }
)

...调用的结果是:

http://localhost/Presentation/ab/cdefg/Transition/1/635802956296104590

当然,这后来无法匹配路由,因为它现在在 URL 中有一个额外的段,原始路由模板不匹配。我希望UrlHelper.Link() 代替生产

http://localhost/Presentation/ab%2Fcdefg/Transition/1/635802956296104590

...然后将匹配(在 urldecode 之前)presentationID="ab%2Fcdefg",然后在 urldecode 之后匹配到 "presentationID=ab/cdefg"

那么为什么UrlHelper.Link() 不转义正斜杠/ 以确保生成正确的链接?

【问题讨论】:

  • 旁注:虽然理论上有效,但我强烈建议避免将这些值作为路径的一部分,因为任何规范化都可能会解码 %2f (即,如果你曾经使用 Uri 来保存它值)
  • @AlexeiLevenkov 是的,尽管这意味着规范化被破坏,因为只有文字 / 可以作为分隔符有效。但是,我无法控制 id 结构,并且坚持我所拥有的,没有将它移动到我想避免的查询。

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


【解决方案1】:

我知道这个问题大约有 1.5 年的历史,但如果我只使用 Uri.EscapeDataString(),我真的无法摆脱双重编码。因此,我提出了这个技巧并为我工作。分享以防万一有人想快速回答。

对于上面的示例

var route = Uri.UnescapeDataString(this.Url.Link(
    RouteNameConstants.PresentationTransition,
    new {
        action = "{0}",
        presentationId = "{1}",  // value: ab/cdefg
        slideIndex = "{2}",  // value: 1
        playStart = "{3}"
    }
)); 
// route will be "http://localhost/Presentation/{1}/{0}/{2}/{3}"
// needs `Uri.UnescapeDataString()` as '{' '}' will be encoded

return string.Format(route,
    ActionNameConstants.PresentationController.Transition,
    Uri.EscapeDataString(presentation.PresentationId),
    slideIndex,
    DateTime.UtcNow.AddMilliseconds(-offsetInMilliseconds).Ticks
);

享受吧!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-29
    • 2015-01-23
    • 1970-01-01
    • 1970-01-01
    • 2016-09-30
    相关资源
    最近更新 更多