Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - Generate Routes Without Http/Request Context

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?

like image 235
bromanko Avatar asked Dec 18 '09 22:12

bromanko


2 Answers

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.

like image 114
Eilon Avatar answered Oct 21 '22 11:10

Eilon


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.

like image 42
Jarrett Meyer Avatar answered Oct 21 '22 10:10

Jarrett Meyer