Get name of virtual directory? - c#

I'm using Request.ApplicationPath to learn the name of the Virtual Directory in which I'm running. Is there a more reliable way?

Request.ApplicationPath is perfectly reliable way of getting the virtual directory and works always when you have the HttpContext and can ask for the Request data.
For further processing and extracting parts of the path, take a look at the VirtualPathUtility class.

You need to use Request.ApplicationPath. That is what it is designed for.
Editing to go with your comment.
Since you want a 'cleaner' way to handle the slash, I recommend creating a utility function that returns the application path with the logic in it to deal with the slash as you see fit.

Use this function in C#:
public static String GetHost()
{
var request = HttpContext.Current.Request;
return request.Url.Scheme + "://" + request.ServerVariables["HTTP_HOST"] + request.ApplicationPath;
}

Related

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).

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;
}

filter duplicate URLs domain from List c#

I have a list of 100,000 urls in list(Of string) which can contain urls in the form.
yahoo.com
http://yahoo.com
http://www.yahoo.com
i have tried using a combination of regex and the Uri class, but that didn't help, so i dumped the code. i also tried using this code, but it will only remove duplicatse of exact form, since its not domain specific.
list = new ArrayList<T>(new HashSet<T>(list))
How filter these duplicates and keep just one of these url if it contains the same name e.g yahoo.
thanks
[EDIT]
Please note that
all URL are of different domains, but can usually have duplicates like the example i gave above
also, am using .net 2.0, so i can't use linq
This worked for me
[TestMethod]
public void TestMethod1()
{
var sites = new List<string> {"yahoo.com", "http://yahoo.com", "http://www.yahoo.com"};
var result = sites.Select(
s =>
s.StartsWith("http://www.")
? s
: s.StartsWith("http://")
? "http://www." + s.Substring(7)
: "http://www." + s).Distinct();
Assert.AreEqual(1, result.Count());
}
I think the Uri Class would be able to help in this case. I am not at a VS machine where I can test; however, pass the Uri constructor the string of the Url, and try the Host property for comparison:
List<string> distinctHosts = new List<string>();
foreach (string url in UrlList)
{
Uri uri = new Uri(url)
if (! disctinctHosts.Contains(uri.Host))
{
distinctHosts.Add(uri.Host);
}
}
This feels a bit primitive, and could probably be more elegant - possibly without a foreach; but like I said, I'm not at a development machine where I could work with it.
I think this would be able to handle any variation of a valid Url. Building an ArrayList is not a good idea; in my opinion, Regex would require that you maintain some sort of custom 'MatchList' that could get unwieldy.
As #Damokles points out, you should have some form of validation. The Uri class does require a protocol: 'http://' or 'ftp://'. You do not want to assume 'badurl.com' is actually invalid; however:
if (!url.StartsWith("http://")) { /* add protocol */ } // then check Host domain as above
...should be sufficient simply to retrieve a distinct host or domain name. I recommend any option that does not require guessing the index position of any part of the Url as that is tightly bound to specific formats.
You can do this with the Uri class and Linq/extension methods. The trick is to normalize the Url before using it with the Uri class. Also note that the Uri class requires the scheme, so that will have to be added for ones where it's not present. You can use a different property of the Uri class to achieve different results. The example below returns all unique Urls and treats yahoo.com differently than www.yahoo.com.
string[] urls = new[] {
"yahoo.com",
"http://yahoo.com",
"http://www.yahoo.com" };
var unique = urls.
Select(url => new System.Uri(
url.StartsWith("http") ? url : "http://" + url).Host).
Distinct();
(Edited to clean up formatting and to make the scheme addition part support both "http://" and "https://")
Try a Regex then .*?(\w+\.\w+)$ assuming you don't have anything after the tld.

ASP.NET Site Redirection help

I am following the code over here https://web.archive.org/web/20211020203216/https://www.4guysfromrolla.com/articles/072810-1.aspx
to redirect http://somesite.com to http://www.somesite.com
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (Request.Url.Authority.StartsWith("www"))
return;
var url = string.Format("{0}://www.{1}{2}",
Request.Url.Scheme,
Request.Url.Authority,
Request.Url.PathAndQuery);
Response.RedirectPermanent(url, true);
}
How can I use this code to handle situations where http://abc.somesite.com should redirect to www.somesite.com
I'd suggest the best way to handle this would be in the dns record, if you have control of it.
If you don't know what the values will be ahead of time, you can use substring with indexof for the Url path to parse out the value you want and replace it.
If you do know what it is ahead of time, you can always just do Request.Url.PathAndQuery.Replace("abc", "www");
You can also do a dns check as #aceinthehole suggested after you have parsed what you need to make sure you haven't made any mistakes.
assuming you have a string like http://abc.site.com and you want to turn abc into www then you could do something like.
string pieceToReplace = Request.Url.PathAndQuery.substring(0, Request.Url.PathAndQuery.IndexOf(".") + 1);
//here I use the scheme and entire url to make sure we don't accidentally replace an "abc" that belongs later in the url like in a word "GHEabc.com" or something.
string newUrl = Request.Url.ToString().Replace(Request.Url.Scheme + "://" + pieceToReplace, Request.Url.Scheme + "://www");
Response.Redirect(newUrl);
p.s. I don't remember if the Request.Url.Scheme already has the "://" in it or not so you will need to edit accordingly.
I don't think you can do it without access to the DNS. It sounds like you need a wildcard DNS entry:
http://en.wikipedia.org/wiki/Wildcard_DNS_record
Along with IIS configured without host headers (IP only). Then you can use code similar to the above to do what you want.
if (!Request.Url.Host.StartsWith ("www") && !Request.Url.IsLoopback)
Response.Redirect('www.somesite.com');
Perhaps tighten it up some to prevent wwww.somesite.com from getting through. Anything that starts with www including wwwmonkeys.somesite.com would get through the above check. It is just an example.
asp.net mvc: How to redirect a non www to www and vice versa

How to get the URL of the current page in C# [duplicate]

This question already has answers here:
Get URL of ASP.Net Page in code-behind [duplicate]
(10 answers)
Closed 9 years ago.
Can anyone help out me in getting the URL of the current working page of ASP.NET in C#?
Try this :
string url = HttpContext.Current.Request.Url.AbsoluteUri;
// http://localhost:1302/TESTERS/Default6.aspx
string path = HttpContext.Current.Request.Url.AbsolutePath;
// /TESTERS/Default6.aspx
string host = HttpContext.Current.Request.Url.Host;
// localhost
You may at times need to get different values from URL.
Below example shows different ways of extracting different parts of URL
EXAMPLE: (Sample URL)
http://localhost:60527/WebSite1test/Default2.aspx?QueryString1=1&QueryString2=2
CODE
Response.Write("<br/>Host " + HttpContext.Current.Request.Url.Host);
Response.Write("<br/>Authority: " + HttpContext.Current.Request.Url.Authority);
Response.Write("<br/>Port: " + HttpContext.Current.Request.Url.Port);
Response.Write("<br/>AbsolutePath: " + HttpContext.Current.Request.Url.AbsolutePath);
Response.Write("<br/>ApplicationPath: " + HttpContext.Current.Request.ApplicationPath);
Response.Write("<br/>AbsoluteUri: " + HttpContext.Current.Request.Url.AbsoluteUri);
Response.Write("<br/>PathAndQuery: " + HttpContext.Current.Request.Url.PathAndQuery);
OUTPUT
Host: localhost
Authority: localhost:60527
Port: 60527
AbsolutePath: /WebSite1test/Default2.aspx
ApplicationPath: /WebSite1test
AbsoluteUri: http://localhost:60527/WebSite1test/Default2.aspx?QueryString1=1&QueryString1=2
PathAndQuery: /WebSite1test/Default2.aspx?QueryString1=1&QueryString2=2
You can copy paste above sample code & run it in asp.net web form application with different URL.
I also recommend reading ASP.Net Routing in case you may use ASP Routing then you don't need to use traditional URL with query string.
http://msdn.microsoft.com/en-us/library/cc668201%28v=vs.100%29.aspx
Just sharing as this was my solution thanks to Canavar's post.
If you have something like this:
"http://localhost:1234/Default.aspx?un=asdf&somethingelse=fdsa"
or like this:
"https://www.something.com/index.html?a=123&b=4567"
and you only want the part that a user would type in then this will work:
String strPathAndQuery = HttpContext.Current.Request.Url.PathAndQuery;
String strUrl = HttpContext.Current.Request.Url.AbsoluteUri.Replace(strPathAndQuery, "/");
which would result in these:
"http://localhost:1234/"
"https://www.something.com/"
if you just want the part between http:// and the first slash
string url = Request.Url.Host;
would return stackoverflow.com if called from this page
Here's the complete breakdown
the request.rawurl will gives the content of current page
it gives the exact path that you required
use HttpContext.Current.Request.RawUrl
If you want to get
localhost:2806
from
http://localhost:2806/Pages/
then use:
HttpContext.Current.Request.Url.Authority
a tip for people who needs the path/url in global.asax file;
If you need to run this in global.asax > Application_Start and you app pool mode is integrated then you will receive the error below:
Request is not available in this context exception in
Application_Start.
In that case you need to use this:
System.Web.HttpRuntime.AppDomainAppVirtualPath
Hope will help others..
A search landed me at this page, but it wasn't quite what I was looking for. Posting here in case someone else looking for what I was lands at this page too.
There is two ways to do it if you only have a string value.
.NET way:
Same as #Canavar, but you can instantiate a new Uri Object
String URL = "http://localhost:1302/TESTERS/Default6.aspx";
System.Uri uri = new System.Uri(URL);
which means you can use the same methods, e.g.
string url = uri.AbsoluteUri;
// http://localhost:1302/TESTERS/Default6.aspx
string host = uri.host
// localhost
Regex way:
Getting parts of a URL (Regex)
I guess its enough to return absolute path..
Path.GetFileName( Request.Url.AbsolutePath )
using System.IO;

Categories