如何自定义编码/解码路由值?

发布于 2024-12-10 20:35:58 字数 991 浏览 3 评论 0原文

我有这条路线:

{controller}/{id}/{action}

因为我认为从 RESTful 的角度来看它更有意义。

问题是 id 可以包含斜杠 (/),即使编码为“%2F”,这些斜杠也会被视为路由分隔符。即使我有这个 Web.config 部分:

<uri>
  <schemeSettings>
    <add name="http" genericUriParserOptions="DontUnescapePathDotsAndSlashes" />
    <add name="https" genericUriParserOptions="DontUnescapePathDotsAndSlashes" />
  </schemeSettings>
</uri>

因为我在中间有 id ,所以我无法采用 {*id} 方法来捕获路由的其余部分包括操作

看起来我唯一的选择是将 / 编码为符合 RFC 的字符,例如 !,但是我不想在控制器内使用临时自定义代码来执行此操作。我希望控制器完整地接收id,并且已经解码。我希望我的 Url.Action 生成正确编码的 URL。对 MVC 的要求是否太多,或者我是否需要分散 ActionFilters 和自定义 URL 帮助程序?

我能找到的唯一方法是放入自定义的IRouteConstraint来操作它接收的RouteValueDictionary。但这听起来像是一个肮脏的黑客:操纵其输入的约束。天知道它的副作用。您认为这是一个足够理智的想法,还是 ASP.NET MVC 中有更好的机制允许这样做?

编辑:此解决方法仅在解析路由时有效,在生成路由时无效。

I have this route:

{controller}/{id}/{action}

Because I think it makes more sense from RESTful perspective.

The problem is that id can contain slashes (/) and those are treated as route separators even when encoded as "%2F". Even when I have this Web.config section in place:

<uri>
  <schemeSettings>
    <add name="http" genericUriParserOptions="DontUnescapePathDotsAndSlashes" />
    <add name="https" genericUriParserOptions="DontUnescapePathDotsAndSlashes" />
  </schemeSettings>
</uri>

Because I have id in the middle I can't employ {*id} approach which captures the rest of the route including the action.

It looks like my only option is to encode / into an RFC compliant character like !, however I do not want to do it using ad-hoc custom code inside controller. I want controller to receive id intact, already decoded. And I want my Url.Action to generate properly encoded URL. Is that too much to ask from MVC, or do I need to scatter ActionFilters and custom URL helpers around?

The only way I could find is to throw in a custom IRouteConstraint to manipulate the RouteValueDictionary it receives. That sounds like a dirty hack though: a constraint manipulating its input. God knows its side effects. Do you think this is a sane enough idea, or is there a better mechanism in ASP.NET MVC allowing that?

EDIT: This workaround only works when parsing the route, not when generating one.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

如何视而不见 2024-12-17 20:35:58

你想做的事无法完成;这已经在 SO 上得到了多次回答 - 特别是最近与 RavenDb 有关,默认情况下在 Id 字段中使用“/”(尽管可以更改)

What you are trying to do cannot be done; this has been answered several times on SO - especially of late in relation to RavenDb which uses "/" in the Id field by default (though this can be changed)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文