directedition
directedition

Reputation: 11705

get server port from Application_Start

I need to be able to fetch the web port being used by my MVC instance on startup, as it may change from site to site. Most answers to how to fetch the port involve getting it from the request object, which doesn't exist in Application_Start. Is there any other way to fetch it?

I tried to fetch it like so:

HttpContext.Current.Request.ServerVariables["SERVER_PORT"] 

But this throws an exception

"System.Web.HttpException (0x80004005): Request is not available in this context"

Upvotes: 2

Views: 1984

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038780

AFAIK this is not possible to be done in Application_Start when hosting in Integrated Pipeline mode in IIS 7+. There's a workaround though involving to use Application_BeginRequest to do a one time application initialization on the first request only. Checkout the following answer: https://stackoverflow.com/a/4243338/29407. This answer has been inspired from the following blog post.

The other possibility is to of course rethink why you need to know the server port at Application_Start and whether you can't do something else.

Upvotes: 3

Related Questions