A peculiarity of URL generation in ASP.NET MVC that often bugged me is that you cannot generate URLs outside of an ASP.NET HttpContext. All built in URL generation classes (HtmlHelper, UrlHelper, LinkBuilder etc.) will throw an exception if called without the right parameters or when HttpContext.Current is null.
This is only because these classes need to know the path of the ASP.NET application they are running in, in order to generate correct relative URLs. For example, a typical website URL can have this form:
http://www.example.com/path/to/application/route/page?parameter=value
In this case our ASP.NET application is hosted under the /path/to/application path. All requests to paths under that application will be forwarded to our app instance and then handled by the ASP.NET routing module. In order to generate links to another page, you can use the full absolute path:
http://www.example.com/path/to/application/route2
or a relative one:
../route2
or, as MVC always does, links that start at the root folder of the host:
/path/to/application/route2
Thus the problem lies in the fact that the host name and the application path can only be found in the current HttpRequest instance. As long as MVC continues to generate URLs in that form, we'll have to manually supply the correct application path in some way when we try to use the URL builders outside of a HttpContext (this is mostly the case when you generate e-mails on a background thread or similar scenarios).




