Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the page origin in razor?

I'm looking for the equivalent of this javascript

window.location.origin

but server side, while building mvc pages.

For example, if you are here http://website.com/123, it would return

http://website.com

Its important that i have the "http://" part

like image 365
odle Avatar asked Aug 06 '12 16:08

odle


Video Answer


1 Answers

I'm a fan of

string url = Request.Url.PathAndQuery.length > 1
  ? Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, string.Empty)
  : url;

Keeps your Http/Https, Port (if applicable), and HostName/IP.

DotNetFiddle Examples

Updated to Account for PathAndQuery length of 1.

like image 95
Erik Philips Avatar answered Oct 19 '22 02:10

Erik Philips