Wednesday, September 17, 2014

...but, I need the tilde in JavaScript!

My superior was not in love with the spaghetti mess I made here in JavaScript in the name of trying to find the url of the root of a web application while also accomodating IIS application scenarios wherein the root of the url may just be http://localhost/yourfoldernamehere where one must not mistake http://localhost/ as the base of things. He suggested that I determine the base of a url in C# (where it is much easier) and then bubble up the value into a hidden form field in HTML from which point it could be slurped into JavaScript. In an ASP.NET MVC controller one may get the base url like so:

var x = Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/");

 
 

Noteworthy: System.Web.VirtualPathUtility.ToAbsolute("~/") has a dance partner in the web forms world in Page.ResolveUrl("~/") (I think) and should just give you a forward slash if you are not doing the IIS application thing. If you are doing the IIS application thing then you will get the name of that second piece of the route after localhost with forward slash bookends. I experimented with @Request.Url.Host.ToLower() and it turned out to be inferior to Request.Url.GetLeftPart(UriPartial.Authority) as it left off the "http://" bit.

No comments:

Post a Comment