Timwi
Timwi

Reputation: 66573

ASP.NET MVC: How to reliably get the real URL of the current request?

Right now I have an MVC application running on http://127.0.0.1:8081/ (it is actually running in the Azure compute emulator). The browser location bar clearly says 8081 for the port number.

However, Request.Url and Request.RawUrl both give me http://127.0.0.1:8082/.

I need to send an e-mail with a URL in it, so I need the correct hostname and port number. How do I get the actual, real URL reliably and without such unexpected deviation?

Upvotes: 3

Views: 3749

Answers (3)

Yakir Manor
Yakir Manor

Reputation: 4829

you can also use:

Request.Url.Host

or use (if you want all the initials and not just the 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 'Abundant Code'
How to Retrieve the Current Domain in ASP.NET MVC?

Upvotes: 3

Neelesh
Neelesh

Reputation: 496

In the cloud as Azure, your process may run anywhere with any port number. the current request will get routed to the process.

that's why you will always have different port number.

It is better that you specify your domain name in the web.config file; it will always be the same for all the request if you read from the config file.

Upvotes: 0

Teoman Soygul
Teoman Soygul

Reputation: 25742

You can use Request.Headers["Host"]; which will give you the host name (or IP) with the correct port number. Then you can reconstruct the URL.

Upvotes: 4

Related Questions