Brian
Brian

Reputation: 25834

Asp.Net Absolute Path of a URL

To make it simpler for a webapp to share files with another app on a different server, I'm using a base href tag in my master page. As many people have discovered, this breaks webform paths. I have a working Form Adaptor class but am not sure how to get the absolute path of the url. Currently, my program is hardcoded to use something akin to :

HttpContext Context = HttpContext.Current;
value = "http://localhost" + Context.Request.RawUrl;

It is worth noting that I'm currently testing on my local IIS server, so there's a strange tendency for a lot of things I've tried using in order what the absolute path do not include the domain name (my local IIS is not visible externally). Which means it isn't an absolute path and thus the base href will wreck it.

Is there a good way to handle this such that it will work locally without hardcoding but will also work properly when uploaded to a server? I'd prefer to avoid anything that involves doing something different on the server-side copy.

Yes, I realize I could use separate web.config files locally and on the server to get this information but this is ugly and violates DRY.

Upvotes: 49

Views: 59696

Answers (5)

Christopher Dunn
Christopher Dunn

Reputation: 11

Using string interpolation:

string redirectUri = $"{this.Request.Url.Scheme}://{this.Request.Url.Authority}{this.Request.ApplicationPath}account/signedout";

Substitute 'this' for 'HttpContext' or 'HttpContext.Current' based on context.

Upvotes: 1

Waqi
Waqi

Reputation: 13

I have used following and it worked for me both client and the server.

string surl = string.Format("{0}://{1}",
    HttpContext.Current.Request.Url.Scheme,
    HttpContext.Current.Request.Url.Authority);

Upvotes: 0

Chris Foster
Chris Foster

Reputation: 1300

Old post but here is another slightly less verbose method

var baseUri = new Uri(HttpContext.Current.Request.Url, "/");

Upvotes: 4

John Rasch
John Rasch

Reputation: 63505

I have used this in the past:

// Gets the base url in the following format: 
// "http(s)://domain(:port)/AppPath"
HttpContext.Current.Request.Url.Scheme 
    + "://"
    + HttpContext.Current.Request.Url.Authority 
    + HttpContext.Current.Request.ApplicationPath;

Upvotes: 113

user799577
user799577

Reputation: 19

Code :

string loginUrl = Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/") + "Login/Login.aspx?UserName=" + LoggedinUser["UserName"] + "&Password=" + LoggedinUser["Password"];

Upvotes: -9

Related Questions