creating absolute URLs that work on both localhost and live site - c#

I want to populate a Literal control with a URL that will work on both my local machine and the live website.
For now, this is what I have:
string TheHost = HttpContext.Current.Request.Url.Host;
string ThePath = HttpContext.Current.Request.Url.AbsolutePath;
string TheProtocol = HttpContext.Current.Request.Url.Scheme;
string TheURL = "SomeText"
The URL that works when I type it manually in the browser looks like this:
http://localhost:12345/ThePageName
but when I run the above code it comes out as
localhost/ThePageName
What do I need to change so that on my local machine I output
http://localhost:12345/ThePageName
and on the live site I get
http://www.example.com/ThePageName

Use the fact that you've already got a Uri via the Request property - you don't need to do it all manually:
Uri pageUri = new Uri(HttpContext.Current.Request.Url, "/ThePageName");
Then build your tag using that - but ideally not just with string concatenation. We don't know enough about what you're using to build the response to say the best way to do it, but if you can use types which know how and when to use URI escaping etc, that will really help.
(I'd also suggest getting rid of your The prefix on every variable, but that's a somewhat different matter...)

Use UriBuilder to modify Urls. Assuming you need to just change path and keep all other parts the same:
var builder = new UriBuilder(HttpContext.Current.Request.Url);
builder.Path = "MyOtherPage";
return builder.Uri;

I don't believe you need to add the hostname for any of your urls in your site.
Just make all your url's relative to the root:
string TheURL = "SomeText"
or
string TheURL = "SomeText"
This will work fine regardless of the hostname.

Or Uri pageUri = new Uri(HttpContext.Current.Request.Url, "ThePageName"); without anti-slash

Just use different key/value in web.config and web.release.config files, and whenever you have to use it, read them from the web.config file.
Here is the example web.config:
<add key="Url" value="http://localhost:58980/" />
Here is the example web.release.config:
<add key="Url" value="http://example.com/" xdt:Transform="Replace" xdt:Locator="Match(key)"/>
This may work. Works for me.

Related

How to maintain the right URL in C#/ASP.NET?

I am given a code and on one of its pages which shows a "search result" after showing different items, it allows user to click on one of records and it is expected to bring up a page so that specific selected record can be modified.
However, when it is trying to bring up the page I get (by IE) "This page cannot be displayed".
It is obvious the URL is wrong because first I see something http://www.Something.org/Search.aspx then it turns into http://localhost:61123/ProductPage.aspx
I did search in the code and found the following line which I think it is the cause. Now, question I have to ask:
What should I do to avoid using a static URL and make it dynamic so it always would be pointing to the right domain?
string url = string.Format("http://localhost:61123/ProductPage.aspx?BC={0}&From={1}", barCode, "Search");
Response.Redirect(url);
Thanks.
Use HttpContext.Current.Request.Url in your controller to see the URL. Url contains many things including Host which is what you're looking for.
By the way, if you're using the latest .Net 4.6+ you can create the string like so:
string url = $"{HttpContext.Current.Request.Url.Host}/ProductPage.aspx?BC={barCode}&From={"Search"}";
Or you can use string.Format
string host = HttpContext.Current.Request.Url.Host;
string url = string.Format("{0}/ProductPage.aspx?BC={1}&From={2}"), host, barCode, "Search";
You can store the Host segment in your AppSettings section of your Web.Config file (per config / environment like so)
Debug / Development Web.Config
Production / Release Web.Config (with config override to replace the localhost value with something.org host)
and then use it in your code like so.
// Creates a URI using the HostUrlSegment set in the current web.config
Uri hostUri = new Uri(ConfigurationManager.AppSettings.Get("HostUrlSegment"));
// does something like Path.Combine(..) to construct a proper Url with the hostName
// and the other url segments. The $ is a new C# construct to do string interpolation
// (makes for readable code)
Uri fullUri = new Uri(hostUri, $"ProductPage.aspx?BC={barCode}&From=Search");
// fullUrl.AbosoluteUri will contain the proper Url
Response.Redirect(fullUri.AbsoluteUri);
The Uri class has a lot of useful properties and methods to give you Relative Url, AbsoluteUrl, your Url Fragments, Host name etc etc.
This should do it.
string url = string.Format("ProductPage.aspx?BC={0}&From={1}", barCode, "Search");
Response.Redirect(url);
If you are using .Net 4.6+ you can also use this string interpolation version
string url = $"ProductPage.aspx?BC={barcode}&From=Search";
Response.Redirect(url);
You should just be able to omit the hostname to stay on the current domain.

strip off prefix of URL's

I have got the following log of URL strings. The logs contain millions of records.
www.example.com/p1?q=k
example.com/p1?q=k
http://example.com/p1?q=k
https://example.com/p1?q=k
http://www.example.com/p1?q=k
I used the C# Uri class but it throws an excepition for format of type "example.com/p1?q=K"
I was wondering if there is a generally/standard accepted method for dealing with such different types of URL to get websitename & the relative URL.
P.S: I could strip off http:// & https:// by using a regex or string comparision, but curious to know if there are any elegant solutions
If you try it with your existing example it will not work.. however you can play around with this and do some appending code where needed which means you will need to create a few variables to store the http://, https://, and www.
System.Uri uriPre = new Uri ("http://www.example.com/p1?q=k");
string uriString = uriPre.Host + uriPre.PathAndQuery;
uriString = uriString.Replace("www.", "");
yields
"example.com/p1?q=k"
the rest of the coding you will have to figure out because only you would know when to utilize the different protocols base on the example I've provided
to expand on Alexei Levenkov answer here is an example that you can use to try to create a new Uri.
Uri tempValue;
var uriPre = new Uri(string.Empty, UriKind.Relative);
if (Uri.TryCreate("example.com/p1?q=k", UriKind.Relative, out tempValue))
{
// do something or retrun tempValue;
}
Uri it the class that is designed to deal with Uris
var noSchemaRelativeUri = new Uri("example.com/foo", UriKind.Relative);
Either UriBuilder or Uri(Uri base, Uri relative) can be used to construct absolute Uri.
To pick between relative and aboslute you can use Uri.TryCreate.
Note. "www.example.com" and "example.com" strictly speaking are unrelated domain names, converting one to another is not guaranteed to always produce registered domain name (also indeed most sites register both and do some sort of redirect between).

Query String from the URL

I have an application URL that can be launched from browser with query string passed in.
My Development URL is
http://localhost:15094/MyPage.html?user=username&role=admin
Client URL will be path to MyPage.html in the hard Drive
file:///C:/Program%20Files/Client/MyPage.html?user=username&role=admin
When the url is localhost with http, i can extract the query string using
System.Windows.Browser.HtmlPage.Document.DocumentUri.Query
// this gives me ?user=username&role=admin
// from http://localhost:15094/MyPage.html?user=username&role=admin
But I want ?user=username&role=admin when client use the URL
file:///C:/Program%20Files/Client/MyPage.html?user=username&role=admin
System.Windows.Browser.HtmlPage.Document.DocumentUri.Query does not work with it I suppose.
Please note Development URL is with http and when the application is installed on a Client's machine, the url will be without http, this is how application should work. Please do not suggest to host it in IIS etc.
My Question is very simple:
How would you extract the query string from "file:///C:/Program%20Files/Client/MyPage.html?user=username&role=admin" ?
If System.Windows.Browser.HtmlPage.Document.DocumentUri.Query works fine for url's without http, why I am not getting query string right?
A simple way to do this without being clever is to use IndexOf eg:
var originalUrl = "file:///C:/Program%20Files/Client/MyPage.html?user=username&role=admin";
var extractedQueryString = string.Empty;
if(originalUrl.IndexOf("?") != -1)
{
extractedQueryString = originalUrl.Substring(originalUrl.IndexOf("?"));
}
Wrote this off the top of my head without compiling but think I got it right.
Also to get the filename part of the string if you're wondering would be:
var extractedFileName = originalUrl.Substring(0, originalUrl.IndexOf("?"));

How to get website name from domain name?

I fetch the domain from the URL as follows:
var uri = new Uri("Http://www.google.com");
var host = uri.Host;
//host ="www.google.com"
But I want only google.com in Host,
host = "google.com"
Given the accepted answer I guess the issue was not knowing how to manipulate strings rather than how to deal with uris... but for anyone else who ends up here:
The Uri class does not have this property so you will have to parse it yourself.
Presumably you do not know what the subdomain is before time so a simple replace may not be possible.
This is not trivial since the TLDs are so varied (http://en.wikipedia.org/wiki/List_of_Internet_top-level_domains), and there maybe be multiple parts to the url (eg http://pre.subdomain.domain.co.uk).
You will have to decide exactly what you want to get and how complex you want the solution to be.
simple - do a string replace, see ekad's answer
medium - regex that works most of the time, see Strip protocol and subdomain from a URL
or complex - refer to a list of suffixes in order to figure out what is subdomain and what is domain eg
Get the subdomain from a URL
If host begins with "www.", you can replace "www." with an empty string using String.Replace Method like this:
var uri = new Uri("Http://www.google.com");
var host = uri.Host.ToLower();
if (host.StartsWith("www."))
{
host = host.Replace("www.", "");
}

Getting full URL from URL with tilde(~) sign

I am trying to get a typical asp.net url starting with the tilde sign ('~') to parse into a full exact url starting with "http:"
I have this string "~/PageB.aspx"
And i want to make it become "http://myServer.com/PageB.aspx"
I know there is several methods to parse urls and get different paths of server and application and such. I have tried several but not gotten the result i want.
Try out
System.Web.VirtualPathUtility.ToAbsolute("yourRelativePath");
There are various ways that are available in ASP.NET that we can use to resolve relative paths to a resource on the server-side and making it available on the client-side. I know of 4 ways -
1) Request.ApplicationPath
2) System.Web.VirtualPathUtility
3) Page.ResolveUrl
4) Page.ResolveClientUrl
Good article : Different approaches for resolving URLs in ASP.NET
If you're in a page handler you could always use the ResolveUrl method to convert the relative path to a server specific path. But if you want the "http://www.yourserver.se" part aswell, you'll have to prepend the Request.Url.Scheme and Request.Url.Authority to it.
string.Format("http://{0}{1}", Request.Url.Host, Page.ResolveUrl(relativeUrl));
This method looks the nicest to me. No string manipulation, it can tolerate both relative or absolute URLs as input, and it uses the exact same scheme, authority, port, and root path as whatever the current request is using:
private Uri GetAbsoluteUri(string redirectUrl)
{
var redirectUri = new Uri(redirectUrl, UriKind.RelativeOrAbsolute);
if (!redirectUri.IsAbsoluteUri)
{
redirectUri = new Uri(new Uri(Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath), redirectUri);
}
return redirectUri;
}

Categories