10

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

tshepang
  • 12,111
  • 21
  • 91
  • 136
odle
  • 5,172
  • 8
  • 29
  • 33
  • Turned out that was already asked... possible duplicate of [How to get current page URL in MVC 3](http://stackoverflow.com/questions/5304782/how-to-get-current-page-url-in-mvc-3) – Alexei Levenkov Aug 06 '12 at 16:07

4 Answers4

14

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.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
1

you could try

@String.Format("{0}://{1}", Request.Url.Scheme, Request.Url.Authority)

Or

@String.Format("{0}://{1}", Request.Url.Scheme, Request.Url.Host)

Authority will include the port number

Manatherin
  • 4,169
  • 5
  • 36
  • 52
0

I think you looking for Request.Url or RawUrl.

Uri.Scheme of Request.Url will give you info on http/https difference.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • Request.Url will also include `/123`. – John H Aug 06 '12 at 16:07
  • @JohnH, I've updated the answer... Also Manatherin's answer(+1) already includes all. – Alexei Levenkov Aug 06 '12 at 16:14
  • Neither of these will give what was requested. Taking the following URL into consideration `http://localhost:63105/home/index`, Request.Url will return `http://localhost:63105/home/index` and Request.RawUrl will return `/home/index`. Both of our answers are inferior to Erik's, so I'll remove mine. – John H Aug 06 '12 at 16:20
-1

The window.location.origin in javascript returns the protocol, port (if any), domain and extension of the current url.

If you want to get the same information from an URL, the accepted answers will provide that to you.

If you want the same behavior, ie a piece of javascript is calling your server method and you want to know where it is calling from, you can inspect the HttpRequest.URLReferrer. However this can be spoofed easily and thus is not reliable.

  • Using `UrlReferrer ` is dangerous! It can be [spoofed / set to anything](https://en.wikipedia.org/wiki/Referer_spoofing). That opens a whole big can of worms if you're not escaping correctly etc. (XSS for example). Also, when I hit the page coming from, say, Google.com your method will return google.com, not website.com. Never trust user-input; the referrer is exactly that. – RobIII Sep 12 '16 at 14:18
  • @RobIII You're correct. Updated my answer to reflect my original opinion. – Jan Van der Haegen Sep 13 '16 at 18:23