ASP.NET MVC - 生成没有 Http/Request 上下文的路由
我希望能够从 RouteCollection 生成 URL,而无需访问 HttpContext。查看 RouteCollection 的实现方式,所有方法都需要访问 RequestContext 才能获取虚拟路径。
我已经通过模拟 HttpContext 解决了这个问题,但这增加了对 RhinoMocks 的尴尬依赖,并且不是一个合理的解决方案。我是否还有其他选项可以在上下文之外生成 URL?
I'd like to be able to generate URLs from a RouteCollection without having access to the HttpContext. Looking at the way RouteCollection is implemented, all methods require access to a RequestContext in order to get the virtual path.
I've worked around this by mocking the HttpContext but this adds an awkward dependency on RhinoMocks and is not a reasonable solution. Do I have other options for generating Urls outside of context?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
确实是一个很好的问题。路由本身确实有一些依赖于从正在运行的 ASP.NET 应用程序调用,例如获取应用程序根 URL 以及 URL 中的任何无 cookie 表单或会话 cookie。虽然创建模拟对象是一种理论上的解决方案,但当然不建议在运行时使用它。
我的建议是在这种情况下根本不要使用路由,并将 URL 硬编码到电子邮件中。电子邮件中的链接必须具有完全限定的 URL(主机名 + 路径),而路由甚至无法生成 URL 的主机名,因此您必须对其进行硬编码。
A great question, indeed. Routing itself does have some dependencies on being called from a running ASP.NET application, such as getting the application root URL as well as any cookieless forms or session cookies that also go in the URL. While creating mock objects is a theoretical solution, it's certainly not recommended for used at runtime.
My recommendation is to not use routing at all for this situation and to hard code the URLs into the emails. Links in an email have to have fully qualified URLs (hostname + path) and routing can't even generate the hostname for the URL, so that's something that you'd already have to hardcode.
抱歉,但是要习惯 MVC 框架中的模拟。一旦你开始测试,你就会需要它。这里有很多东西:HttpContext、Session、Server——所有东西都会泄漏到你的控制器中。如果你想生成路径,你要么需要与 HttpContext 对话(在 MVC 中,这实际上是 HttpContextBase,所以我猜你可以编写自己的具体实现),或者你需要模拟它。
Sorry, but get used to mocking in the MVC framework. As soon as you get into testing, you're going to need it. There's so much there: HttpContext, Session, Server - all things that leak into your controller. If you want to generate the path, you either need to talk to the HttpContext (in MVC, this is actually HttpContextBase, so you can write your own concrete implementation I guess), or you need to mock it.