5

I am trying to get the application url in C#. I have tried using:

HttpContext.Current.Request.ApplicationPath 

But that only returns me "/". I am trying to get the full url of application's base url, which may or may not simply be "something.com". In some cases, depending on the environment, it is "something.com/foo/bar".

How can I achieve this?

girlcode
  • 3,155
  • 5
  • 27
  • 41
  • Is your application running as a virtual directory, or behind a reverse proxy? `Request.ApplicationPath` has always worked for me in the past. – Steven V Aug 05 '13 at 19:20
  • Throw a debugger somewhere and inspect `HttpContext.Current.Request` and `HttpContext.Current.Request.Url`- you'll find a ton of useful properties which give you the URL formatted lots of ways - one of them is probably going to be what you're looking for. – Joe Enos Aug 05 '13 at 19:20

2 Answers2

8

Wouldn't the RawUrl be enough for you?

If that gives you too much, you could try

VirtualPathUtility.ToAbsolute("~/");
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
7

Try this:

string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/');
Karl Anderson
  • 34,606
  • 12
  • 65
  • 80
  • this much worked fine for me Request.Url.Scheme + "://" + Request.Url.Authority. +1 for this :) – tariq Mar 27 '14 at 08:37
  • This will not work when application is starting e.g. in Global.asax methods, class static initializers ... – AaA Jan 05 '23 at 02:56