WebApi的UrlHelper.Link()不会转义正斜杠(/)

时间:2015-10-13 02:34:05

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

我对UrlHelper.Link()没有转义routeValues中存在的正斜杠感到有点困惑,并且生成的网址与Link()生成网址的路线不匹配。以下是我遇到的具体示例:

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

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()不会转义正斜杠/以确保生成正确的链接?

1 个答案:

答案 0 :(得分: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
);

享受!