3

I need to set up a bunch of paths and URLs when my app starts, ie in global.asax. Using UrlHelper.Content() is the easiest way to do that, but it is not available for use.

So how can I get an instance of it inside global.asax? I tried creating one, but of course RequestContext doesn't exist.

The answer most linked-to is here but that throws exceptions for me. I am using the latest MVC3.

Community
  • 1
  • 1
merom4
  • 33
  • 3

1 Answers1

5

The code that you have linked to doesn't work for you because you are probably running your application in IIS 7 Integrated Mode (in contrast to Classic Mode). In integrated mode you have no access to the HttpContext in Application_Start. So if on all price you need to generate urls in your Application_Start method forget about UrlHelper, you will need some other method. This being said you could of course use this code in events like Application_BeginRequest, ...

And by the way it's strange that you need to generate urls there. I have never had such need. Maybe you could explain your scenario in more details in order to get a more adapted solution to it.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • I am running IIS Express on a dev machine. When we launch it will be in shared hosting. What are the implications? Do you mean I should look for a different way to solve the problem? – merom4 Jul 15 '11 at 18:08
  • @merom4, IIS Express configures by default Integrated Mode which explains why your code doesn't work. I don't know what is your scenario nor why you need to generate url, nor where/in which method precisely. So I cannot give you more specific answer. – Darin Dimitrov Jul 15 '11 at 18:11
  • In summary, I have a static class with all sorts of urls and paths to external resources, images, logs, etc. And when the app starts I need to set some stuff in there, like the app root. – merom4 Jul 15 '11 at 18:12
  • If I cant access UrlHelper, my question I guess is, given some absolute path, how can I convert it to a relative one so I can serve it... for eg "/blah/blah/mysite/images/image.png" to "/images/image.png"? – merom4 Jul 15 '11 at 18:13
  • @merom4, you will have to find some alternative method to initialize those values, not in Application_Start. As I said you don't have access to the HttpContext if you run in Integrated Mode. Also what you have shown in your comment are two relative paths. – Darin Dimitrov Jul 15 '11 at 18:14