Reputation: 1385
How can I get the URL of the server my MVC3 project is being executed on? I do NOT want to hard code a server address.
I've got three servers I will be working with:
None of the above servers have the same URL.
My web project needs to generate notification emails that contain a clickable link.
I know that Request.Url.ToString() will get me the server but if possible, I'd rather not spend time processing that string everytime I generate an email.
Upvotes: 3
Views: 7106
Reputation:
you can use Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);
. This will return the sever starting from http.... till the server name and port.
Upvotes: 0
Reputation: 17964
HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.ApplicationPath;
Should do the trick for you
Upvotes: 2
Reputation: 26143
Not sure if this is what you're after, but I recently had to get the URL of the default website on IIS. It proved to be a real pain, but I managed to get this working code...
using System.DirectoryServices;
using System.Diagnostics;
private string GetDefaultSite()
{
using (DirectoryEntry w3svc2 = new DirectoryEntry("IIS://Localhost/W3SVC"))
{
foreach (DirectoryEntry de in w3svc2.Children)
{
if (de.SchemaClassName == "IIsWebServer" &&
de.Properties["ServerComment"].Value.ToString() == "Default Web Site")
{
string binding = de.Properties["ServerBindings"].Value.ToString();
string[] split = binding.Split(':');
if (split[2] == "") return "http://localhost/";
else return "http://" + split[2] + "/";
}
}
}
return "";
}
Upvotes: 1
Reputation: 1405
One of these should work:
Response.Write Server.MachineName;
Response.Write Request.ServerVariables["LOCAL_ADDR"];
Upvotes: -1
Reputation: 14874
Look at the Server Variables, you can find the server name there.
SERVER_NAME
could be a good choice.
Upvotes: 0
Reputation: 46311
You can process the Request.Url
once and store the result in a static variable. Just make sure you access that variable in a thread-safe manner. I've been using this in production for quite a while, and it works like a charm.
Upvotes: 5
Reputation: 30152
Request.URI is the way to go. If you are really that worried about performance, profile it. I can almost guarantee the results wont be bad. If they are you can read it from the headers manually via Request.ServerVariables["HTTP_HOST"] Request.ServerVariables["SERVER_NAME"] etc
Upvotes: 1