ASP.NET MVC: how to reliably get the real url of the current request?

Right now I have an MVC app running at (it's actually running in the Azure Compute Emulator). The browser location bar explicitly states 8081 for the port number.

However Request.Url

, Request.RawUrl

both give me .

I need to send an email with the url in it, so I need the correct hostname and port number. How can I get the real real url and without such an unexpected deviation?


source to share

3 answers

You can use Request.Headers["Host"];

which will give you the hostname (or IP) with the correct port number. Then you can recover the url.



you can also use:



or use (if you want all initials, not just host):

public ActionResult Index()
string Domain = Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host +       (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port);
return View(Domain);


this was taken from "Rich Code"
How do I get the current domain in ASP.NET MVC?



In a cloud like Azure, your process can run anywhere with any port number. the current request will be redirected to the process.

why you will always have a different port number.

Better to specify your domain name in the web.config file; it will always be the same for the whole request if you read from the config file.



All Articles