How to remove the port number from a url string - c#

I have the following code snippet:
string tmp = String.Format("<SCRIPT FOR='window' EVENT='onload' LANGUAGE='JavaScript'>javascript:window.open('{0}');</SCRIPT>", url);
ClientScript.RegisterClientScriptBlock(this.GetType(), "NewWindow", tmp);
The URL generated by this code include the port number and I think that is happening because port 80 is used by the website and in this code I am trying to load a page from a virtual directory of the website. Any ideas on how to suppress the port number in the URL string generated by this code?

Use the Uri.GetComponents method. To remove the port component you'll have to combine all the other components, something like:
var uri = new Uri( "http://www.example.com:80/dir/?query=test" );
var clean = uri.GetComponents( UriComponents.Scheme |
UriComponents.Host |
UriComponents.PathAndQuery,
UriFormat.UriEscaped );
EDIT: I've found a better way:
var clean = uri.GetComponents( UriComponents.AbsoluteUri & ~UriComponents.Port,
UriFormat.UriEscaped );
UriComponents.AbsoluteUri preservers all the components, so & ~UriComponents.Port will only exclude the port.

UriBuilder u1 = new UriBuilder( "http://www.example.com:80/dir/?query=test" );
u1.Port = -1;
string clean = u1.Uri.ToString();
Setting the Port property to -1 on UriBuilder will remove any explicit port and implicitly use the default port value for the protocol scheme.

A more generic solution (works with http, https, ftp...) based on Ian Flynn idea.
This method does not remove custom port, if any.
Custom port is defined automatically depending on the protocol.
var uriBuilder = new UriBuilder("http://www.google.fr/");
if (uriBuilder.Uri.IsDefaultPort)
{
uriBuilder.Port = -1;
}
return uriBuilder.Uri.AbsoluteUri;
April 2021 update
With newer .NET versions, Uri.AbsoluteUri removes the default ports and retains the custom port by default. The above code-snippet is equivalent to:
var uriBuilder = new UriBuilder("http://www.google.fr/");
return uriBuilder.Uri.AbsoluteUri;

I would use the System.Uri for this. I have not tried, but it seems it's ToString will actually output what you want:
var url = new Uri("http://google.com:80/asd?qwe=asdff");
var cleanUrl = url.ToString();
If not, you can combine the components of the url-members to create your cleanUrl string.

var url = "http://google.com:80/asd?qwe=zxc#asd";
var regex = new Regex(#":\d+");
var cleanUrl = regex.Replace(url, "");
the solution with System.Uri is also possible but will be more bloated.

You can use the UriBuilder and set the value of the port to -1
and the code will be like this:
Uri tmpUri = new Uri("http://LocalHost:443/Account/Index");
UriBuilder builder = new UriBuilder(tmpUri);
builder.Port = -1;
Uri newUri = builder.Uri;

You can also use the properties of URIBuilder for this, it has properties for outputting an url the way you want

Ok, thanks I figured it out...used the KISS principle...
string redirectstr = String.Format(
"http://localhost/Gradebook/AcademicHonestyGrid.aspx?StudentID={0}&ClassSectionId={1}&uid={2}",
studid,
intSectionID,
HttpUtility.UrlEncode(encrypter.Encrypt(uinfo.ToXml())));
Response.Redirect(redirectstr );
works fine for what I am doing which is a test harness

Related

Bug? System.UriFormatException: Invalid URI: The URI scheme is not valid

The strings are identical but when passed as a variable it is not valid?
What the hell is going on? Is it a language bug? I'm running this in C# .Net Core
var postUrl = "​http://www.contoso.com";
var postUri = new Uri("http://www.contoso.com"); // works
var uri = new Uri(postUrl); // does not work
If you pulling your hair, then it because there is space after first opening quote in postUrl. Please remove that space & your bug will be begone.
Worked around the problem by using.
var postUrl = "​http://www.contoso.com";
var uriBuilder = new UriBuilder(postUrl);
var uri = uriBuilder.Uri
Still wondering wtf?
Just the daily wtf of a programmer doing his job.

Remove additional slashes from URL

In ASP.Net it is posible to get same content from almost equal pages by URLs like
localhost:9000/Index.aspx and localhost:9000//Index.aspx or even localhost:9000///Index.aspx
But it isn't looks good for me.
How can i remove this additional slashes before user go to some page and in what place?
Use this :
url = Regex.Replace(url , #"/+", #"/");
it will support n times
see
https://stackoverflow.com/a/19689870
https://msdn.microsoft.com/en-us/library/9hst1w91.aspx#Examples
You need to specify a base Uri and a relative path to get the canonized behavior.
Uri baseUri = new Uri("http://www.contoso.com");
Uri myUri = new Uri(baseUri, "catalog/shownew.htm");
Console.WriteLine(myUri.ToString());
This solution is not that pretty but very easy
do
{
url = url.Replace("//", "/");
}
while(url.Contains("//"));
This will work for many slashes in your url but the runtime is not that great.
Remove them, for example:
url = url.Replace("///", "/").Replace("//", "/");
Regex.Replace("http://localhost:3000///////asdasd/as///asdasda///asdasdasd//", #"/+", #"/").Replace(":/", "://")
Here is the code snippets for combining URL segments, with the ability of removing the duplicate slashes:
public class PathUtils
{
public static string UrlCombine(params string[] components)
{
var isUnixPath = Path.DirectorySeparatorChar == '/';
for (var i = 1; i < components.Length; i++)
{
if (Path.IsPathRooted(components[i])) components[i] = components[i].TrimStart('/', '\\');
}
var url = Path.Combine(components);
if (!isUnixPath)
{
url = url.Replace(Path.DirectorySeparatorChar, '/');
}
return Regex.Replace(url, #"(?<!(http:|https:))//", #"/");
}
}

How can I get the baseurl of site?

I want to write a little helper method which returns the base URL of the site. This is what I came up with:
public static string GetSiteUrl()
{
string url = string.Empty;
HttpRequest request = HttpContext.Current.Request;
if (request.IsSecureConnection)
url = "https://";
else
url = "http://";
url += request["HTTP_HOST"] + "/";
return url;
}
Is there any mistake in this, that you can think of? Can anyone improve upon this?
Try this:
string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority +
Request.ApplicationPath.TrimEnd('/') + "/";
string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority)
That's it ;)
The popular GetLeftPart solution is not supported in the PCL version of Uri, unfortunately. GetComponents is, however, so if you need portability, this should do the trick:
uri.GetComponents(
UriComponents.SchemeAndServer | UriComponents.UserInfo, UriFormat.Unescaped);
This is a much more fool proof method.
VirtualPathUtility.ToAbsolute("~/");
I believe that the answers above doesn't consider when the site is not in the root of the website.
This is a for WebApi controller:
string baseUrl = (Url.Request.RequestUri.GetComponents(
UriComponents.SchemeAndServer, UriFormat.Unescaped).TrimEnd('/')
+ HttpContext.Current.Request.ApplicationPath).TrimEnd('/') ;
To me, #warlock's looks like the best answer here so far, but I've always used this in the past;
string baseUrl = Request.Url.GetComponents(
UriComponents.SchemeAndServer, UriFormat.UriEscaped)
Or in a WebAPI controller;
string baseUrl = Url.Request.RequestUri.GetComponents(
UriComponents.SchemeAndServer, UriFormat.Unescaped)
which is handy so you can choose what escaping format you want. I'm not clear why there are two such different implementations, and as far as I can tell, this method and #warlock's return the exact same result in this case, but it looks like GetLeftPart() would also work for non server Uri's like mailto tags for instance.
I go with
HttpContext.Current.Request.ServerVariables["HTTP_HOST"]
Based on what Warlock wrote, I found that the virtual path root is needed if you aren't hosted at the root of your web. (This works for MVC Web API controllers)
String baseUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority)
+ Configuration.VirtualPathRoot;
I'm using following code from Application_Start
String baseUrl = Path.GetDirectoryName(HttpContext.Current.Request.Url.OriginalString);
This works for me.
Request.Url.OriginalString.Replace(Request.Url.PathAndQuery, "") + Request.ApplicationPath;
Request.Url.OriginalString: return the complete path same as browser showing.
Request.Url.PathAndQuery: return the (complete path) - (domain name + PORT).
Request.ApplicationPath: return "/" on hosted server and "application name" on local IIS deploy.
So if you want to access your domain name do consider to include the application name in case of:
IIS deployment
If your application deployed on the sub-domain.
====================================
For the dev.x.us/web
it return this
strong text
Please use the below code                           
string.Format("{0}://{1}", Request.url.Scheme, Request.url.Host);
you could possibly add in the port for non port 80/SSL?
something like:
if (HttpContext.Current.Request.ServerVariables["SERVER_PORT"] != null && HttpContext.Current.Request.ServerVariables["SERVER_PORT"].ToString() != "80" && HttpContext.Current.Request.ServerVariables["SERVER_PORT"].ToString() != "443")
{
port = String.Concat(":", HttpContext.Current.Request.ServerVariables["SERVER_PORT"].ToString());
}
and use that in the final result?

Path equivalent in asp.net (C#)?

Whats the equivalent to System.IO.Path ?
I got this url: http://www.website.com/category1/category2/file.aspx?data=123
How can i break this down, like
var url = ASPNETPATH("http://www.website.com/category1/category2/file.aspx?data=123");
url.domain <-- this would then return http://www.website.com
url.folder <-- would return category1/category2
url.file <-- would return file.aspx
url.queryString <-- would return the querystring in some format
Use the UriBuilder class:
http://msdn.microsoft.com/en-us/library/system.uribuilder.aspx
UriBuilder uriBuilder = new UriBuilder("http://www.somesite.com/requests/somepage.aspx?i=123");
string host = uriBuilder.Host; // www.somesite.com
string query = uriBuilder.Query; // ?i=123
string path = uriBuilder.Path; // /requests/somepage.aspx
Check out the URI Class you can get all of that information using that class.
Regular expressions are perfect to use for this.
Here's a link that has some nice info on using them.
http://www.regular-expressions.info/
Edit : I forgot C# has a URI class which you can use for this as well.

What is the quickest way to get the absolute uri for the root of the app in asp.net?

What is the simplest way to get: http://www.[Domain].com in asp.net?
There doesn't seem to be one method which can do this, the only way I know is to do some string acrobatics on server variables or Request.Url. Anyone?
We can use Uri and his baseUri constructor :
new Uri(this.Request.Url, "/") for the root of the website
new Uri(this.Request.Url, this.Request.ResolveUrl("~/")) for the root of the website
You can do it like this:
string.Format("{0}://{1}:{2}", Request.Url.Scheme, Request.Url.Host, Request.Url.Port)
And you'll get the generic URI syntax <protocol>://<host>:<port>
You can use something like this.
System.Web.HttpContext.Current.Server.ResolveUrl("~/")
It maps to the root of the application. now if you are inside of a virtual directory you will need to do a bit more work.
Edit
Old posting contained incorrect method call!
I really like the way CMS handled this question the best, using the String.Format, and the Page.Request variables. I'd just like to tweak it slightly. I just tested it on one of my pages, so, i'll copy the code here:
String baseURL = string.Format(
(Request.Url.Port != 80) ? "{0}://{1}:{2}" : "{0}://{1}",
Request.Url.Scheme,
Request.Url.Host,
Request.Url.Port)
System.Web.UI.Page.Request.Url
this.Request.Url.Host
I use this property on Page to handle cases virtual directories and default ports:
string FullApplicationPath {
get {
StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}://{1}", Request.Url.Scheme, Request.Url.Host);
if (!Request.Url.IsDefaultPort)
sb.AppendFormat(":{0}", Request.Url.Port);
if (!string.Equals("/", Request.ApplicationPath))
sb.Append(Request.ApplicationPath);
return sb.ToString();
}
}
This method handles http/https, port numbers and query strings.
'Returns current page URL
Function fullurl() As String
Dim strProtocol, strHost, strPort, strurl, strQueryString As String
strProtocol = Request.ServerVariables("HTTPS")
strPort = Request.ServerVariables("SERVER_PORT")
strHost = Request.ServerVariables("SERVER_NAME")
strurl = Request.ServerVariables("url")
strQueryString = Request.ServerVariables("QUERY_STRING")
If strProtocol = "off" Then
strProtocol = "http://"
Else
strProtocol = "https://"
End If
If strPort <> "80" Then
strPort = ":" & strPort
Else
strPort = ""
End If
If strQueryString.Length > 0 Then
strQueryString = "?" & strQueryString
End If
Return strProtocol & strHost & strPort & strurl & strQueryString
End Function
I had to deal with something similar, I needed a way to programatically set the tag to point to my website root.
The accepted solution wasn't working for me because of localhost and virtual directories stuff.
So I came up with the following solution, it works on localhost with or without virtual directories and of course under IIS Websites.
string.Format("{0}://{1}:{2}{3}", Request.Url.Scheme, Request.Url.Host, Request.Url.Port, ResolveUrl("~")
Combining the best of what I've seen on this question so far, this one takes care of:
http and https
standard ports (80, 443) and non standard
application hosted in a sub-folder of the root
string url = String.Format(
Request.Url.IsDefaultPort ? "{0}://{1}{3}" : "{0}://{1}:{2}{3}",
Request.Url.Scheme, Request.Url.Host,
Request.Url.Port, ResolveUrl("~/"));

Categories