Reputation: 33880
If my ASP.NET MVC application is deployed at the url http://www.foobar.com/app, then I want to be able to get this root Url.
I want to therefore do this at some place:
var scheme = HttpContext.Current.Request.Url.Scheme;
var host = HttpContext.Current.Request.Url.Host;
var port = HttpContext.Current.Request.Url.IsDefaultPort
?
string.Empty : string.Format(":{0}", HttpContext.Current.Request.Url.Port);
var applicationRootUrl =
string.Format("{0}://{1}{2}", scheme, host, port);
Option A
If I do it in the Application_Start
even in Global.asax
, the HttpContext.Current.Request
is not available at that time.
Option B
I could do it in some event where a user request arrives (BeginRequest
, I think or something. Don't know its name but can look it up), and check if I already have the base path then I don't reconstruct the path, otherwise I do construct the path of the application.
Option C I could write an HTTP Module or an Action Filter for this.
However, options B and C will compromise performance slightly as they will perform this check with every request, even though they will only construct the Url with the first request.
So, where do I construct the base url of my application?
PS: I am using ASP.NET MVC 5.2.3 and targeting v4.6 of the .NET framework (and hence v4.6 of ASP.NET as well).
Upvotes: 1
Views: 182
Reputation: 2201
You can construct the RootURI once time and store it somewhere (Application variable, Memory Cache, ...) then reuse it later.
For example:
public static GetRootUri()
{
if (Application["RootUri"] == null)
{
var rootUri = ConstructRootUriHere();
Application["RootUri"] = rootUri;
}
return Application["RootUri"] as string;
}
Anyway I do not think you need to do this as it should not affect performance at all so it is not worth it.
Upvotes: 1