Taking params from a url - c#

Take these two URLs:
www.mySite.com?name=ssride360
www.mySite.com/ssride360
I know that to get the name param from url 1 you would do:
string name = Request.Params['name'];
But how would I get that for the second url?
I was thinking about attempting to copy the url and remove the known information (www.mySite.com) and then from there I could set name to the remainder.
How would I do a url copy like that? Is there a better way to get 'ssride360' from the second url?
Edit Looking on SO I found some info on copying URLs
string url = HttpContext.Current.Request.Url.AbsoluteUri;
// http://localhost:1302/TESTERS/Default6.aspx
string path = HttpContext.Current.Request.Url.AbsolutePath;
// /TESTERS/Default6.aspx
Is this the best way for me? each url have one additional param (mySite.com/ssride360?site=SO) for example. Also I know that mySite.com/ssride360 would reference a folder in my project so wouldn't i be getting that file along with it (mySite.com/ssride360/Default6.aspx)?
At this point I think there are better ways then a url copy.
Suggestions?

Uri x = new Uri("http://www.mySite.com/ssride360");
Console.WriteLine (x.AbsolutePath);
prints /ssride360

This method will allow you to get the name even if there is something after it. It is also a good model to use if you plan on putting other stuff after the name and want to get those values.
char [] delim = new char[] {'/'};
string url = "www.mySite.com/ssride360";
string name = url.Split(delim)[1];
Then if you had a URL that included an ID after the name you could do:
char [] delim = new char[] {'/'};
string url = "www.mySite.com/ssride360/abc1234";
string name = url.Split(delim)[1];
string id = url.Split(delim)[2];

URL rewriting is a common solution for this problem. You give it the patterns of the URL's you want to match and what it needs to change it into. So it would detect www.mySite.com/ssride360 and transform it into www.mySite.com?name=ssride360. The user of the website sees the original URL and doesn't know anything changed, but your code sees the transformed URL so you can access the variables in the normal way. Another big plus is that the rules allow you to set the patterns that get transformed as well as the ones that just get passed through to actual folders / files.
http://learn.iis.net/page.aspx/461/creating-rewrite-rules-for-the-url-rewrite-module/

Like javascript? If so...
<script type="text/javascript">
function getName() {
var urlParts = window.location.pathname.split('/'); //split the URL.
return urlParts[1]; //get the value to the right of the '/'.
}
</script>

Related

How can I make a string out of a complex URL address

I've been trying to make this URL a workable string in C#, but unfortunately using extra "" or "#" is not cutting it. Even breaking it into smaller strings is proving difficult. I want to be able to convert the entire address into a single string.
this is the full address:
<https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT="+URLEncode(""+[Material].[Material - Key])+"&lsIZV_MAT=>
I've also tried this:
string url = #"https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=";
string url2 = #"+ URLEncode("" +[Material].[Material - Key]) + """"";
string url3 = #"&lsIZV_MAT=";
Any help is appreciated.
The simplest solution is put additional quotes inside string literal and use string.Concat to join all of them into single URL string:
string url = #"https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=";
string url2 = #"""+URLEncode(""+[Material].[Material - Key])+""";
string url3 = #"&lsIZV_MAT=";
string resultUrl = string.Concat(url, url2, url3);
NB: You can use Equals method or == operator to check if the generated string matches with desired URL string.
This may be a bit of a workaround rather than an actual solution but if you load the string from a text file and run to a breakpoint after it you should be able to find the way the characters are store or just run it from that.
You may also have the issue of some of the spaces you've added being left over which StringName.Replace could solve if that's causing issues.
I'd recommend first checking what exactly is being produced after the third statement and then let us know so we can try and see the difference between the result and original.
You are missing the triple quotes at the beginning of url2
string url = #"https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=";
string url2 = #"""+URLEncode(""+[Material].[Material - Key])+""";
string url3 = #"&lsIZV_MAT=";
I just made two updates
t&lsMZV_MAT=" to t&lsMZV_MAT="" AND
[Material - Key])+" to [Material - Key])+""
string s = #"<https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=""+ URLEncode([Material].[Material - Key])+""&lsIZV_MAT=>";
Console.Write(s);
Console.ReadKey();

C# cut file Name from Path

I am creating an Image Extraction tool and I am able to retrieve the Images with full path..
For Example:
I need to cut the File name (rss) from path...
I search posts and Tried following
//1.
//string str = s.Split('/', '.')[1];
//2.
string s1;
// string fileName = "abc.123.txt";
int fileExtPos = s.LastIndexOf(".");
if (fileExtPos >= 0)
s1 = s.Substring(0, fileExtPos);
//3.
//var filenames = String.Join(
// ", ",
// Directory.GetFiles(#"c:\", "*.txt")
// .Select(filename =>
//4.
// Path.GetFileNameWithoutExtension(filename)));
None seems to be working
I want the name between "images" and "png" ..What can be the exact code?
Any Suggestion will be helpful
Just use the class Path and its method GetFileNameWithoutExtension
string file = Path.GetFileNameWithoutExtension(s);
Warning: In this context (just the filename without extension and no arguments passed after the URL) the method works well, however this is not the case if you use other methods of the class like GetDirectoryName. In that context the slashes are reversed into Windows-style backslashes "\" and this could be an error for other parts of your program
Another solution, probably more WEB oriented is through the class Uri
Uri u = new Uri(s);
string file = u.Segments.Last().Split('.')[0];
but I find this a lot less intuitive and more error prone.
In your example you're using a uri so you should use System.Uri
System.Uri uri = new System.Uri(s);
string path = uri.AbsolutePath;
string pathWithoutFilename = System.IO.Path.GetDirectoryName(path);
Why use Uri? Because it will handle things like
http://foo.com/bar/file.png#notthis.png
http://foo.com/bar/file.png?key=notthis.png
http://foo.com/bar/file.png#moo/notthis.png
http://foo.com/bar/file.png?key=moo/notthis.png
http://foo.com/bar/file%2epng
Etc.
Here's a fiddle
You should use the various System.IO.Path functions to manipulate paths as they work cross platform. Similarly you should use the System.Uri class to manipulate Uris as it will handle all the various kinds of edge cases like escaped characters, fragments, query strings, etc.

How to retrieve the locale(country) code from URL?

I have a URL, which is like http://example.com/UK/Deal.aspx?id=322
My target is to remove the locale(country) part, to make it like http://example.com/Deal.aspx?id=322
Since the URL may have other similar formats like: https://ssl.example.com/JP/Deal.aspx?id=735, using "substring" function is not a good idea.
What I can think about is to use the following method for separating them, and map them back later.
HttpContext.Current.Request.Url.Scheme
HttpContext.Current.Request.Url.Host
HttpContext.Current.Request.Url.AbsolutePath
HttpContext.Current.Request.Url.Query
And, suppose HttpContext.Current.Request.Url.AbsolutePath will be:
/UK/Deal.aspx?id=322
I am not sure how to deal with this since my boss asked me not to use "regular expression"(he thinks it will impact performance...)
Except "Regular Expression", is there any other way to remove UK from it?
p.s.: the UK part may be JP, DE, or other country code.
By the way, for USA, there is no country code, and the url will be http://example.com/Deal.aspx?id=322
Please also take this situation into consideration.
Thank you.
Assuming that you'll have TwoLetterCountryISOName in the Url. yYou can use UriBuilder class to remove the path from Uri without using the Regex.
E.g.
var originalUri = new Uri("http://example.com/UK/Deal.aspx?id=322");
if (IsLocaleEnabled(sourceUri))
{
var builder = new UriBuilder(sourceUri);
builder.Path
= builder.Path.Replace(sourceUri.Segments[1] /* remove UK/ */, string.Empty);
// Construct the Uri with new path
Uri newUri = builder.Uri;;
}
Update:
// Cache the instance for performance benefits.
static readonly Regex regex = new Regex(#"^[aA-zZ]{2}\/$", RegexOptions.Compiled);
/// <summary>
/// Regex to check if Url segments have the 2 letter
/// ISO code as first ocurrance after root
/// </summary>
private bool IsLocaleEnabled(Uri sourceUri)
{
// Update: Compiled regex are way much faster than using non-compiled regex.
return regex.IsMatch(sourceUri.Segments[1]);
}
For performance benefits you must cache it (means keep it in static readonly field). There's no need to parse a pre-defined regex on every request. This way you'll get all the performance benefits you can get.
Result - http://example.com/Deal.aspx?id=322
It all depends on whether the country code always has the same position. If it's not, then some more details on the possible formats are required.. Maybe you could check, if the first segment has two chars or something, to be sure it really is a country code (not sure if this is reliable though). Or you start with the filename, if it's always in the format /[optionalCountryCode]/deal.aspx?...
How about these two approaches (on string level):
public string RemoveCountryCode()
{
Uri originalUri = new Uri("http://example.com/UK/Deal.aspx?id=322");
string hostAndPort = originalUri.GetLeftPart(UriPartial.Authority);
// v1: if country code is always there, always has same position and always
// has format 'XX' this is definitely the easiest and fastest
string trimmedPathAndQuery = originalUri.PathAndQuery.Substring("/XX/".Length);
// v2: if country code is always there, always has same position but might
// not have a fixed format (e.g. XXX)
trimmedPathAndQuery = string.Join("/", originalUri.PathAndQuery.Split('/').Skip(2));
// in both cases you need to join it with the authority again
return string.Format("{0}/{1}", hostAndPort, trimmedPathAndQuery);
}
If the AbsolutePath will always have the format /XX/...pagename.aspx?id=### where XX is the two letter country code, then you can just strip off the first 3 characters.
Example that removes the first 3 characters:
var targetURL = HttpContext.Current.Request.Url.AbsolutePath.Substring(3);
If the country code could be different lengths, then you could find the index of the second / character and start the substring from there.
var sourceURL = HttpContext.Current.Request.Url.AbsolutePath;
var firstOccurance = sourceURL.IndexOf('/')
var secondOccurance = sourceURL.IndexOf('/', firstOccurance);
var targetURL = sourceURL.Substring(secondOccurance);
The easy way would be to treat as string, split it by the "/" separator, remove the fourth element, and then join them back with the "/" separator again:
string myURL = "https://ssl.example.com/JP/Deal.aspx?id=735";
List<string> myURLsplit = myURL.Split('/').ToList().RemoveAt(3);
myURL = string.Join("/", myURLsplit);
RESULT: https://ssl.example.com/Deal.aspx?id=735

How to get onyl part of the URL in c#

I am creating a module using C# which will need to refer the URL
So i have 2 example URLs for you here.
http://www.website.com/ProductDetail/tabid/86/rvdsfpid/1gb-dual-port-iscsi-8660/rvdsfmfid/qlogic-174/Default.aspx
&&
http://www.website.com/ProductDetail/tabid/86/rvdsfpid/49950/default.aspx
Now what i need from both the URls is the product ID which in the first case is 8660 & the second case is 49950. I cannot change the way these URls are generated. The easiest way would have been
http://www.website.com/ProductDetail/tabid/86/default.aspx?rvdsfpid=49950
and then i could do the following and life would be easy.
string Pid= Request.Querystring["rvdsfpid"];
However since i dont have control on the way the URL is generatyed how can i catch the URL and fetch only the productId.
Assuming that's the URL format you're being passed and there's nothing else you can do....You're going to need to get the full url and then split it. Here's the basic, you're going to have to add some extra checks and stuff in there;
string url = "http://www.website.com/ProductDetail/tabid/86/rvdsfpid/1gb-dual-port-iscsi-8660/rvdsfmfid/qlogic-174/Default.aspx"
//string url = "http://www.website.com/ProductDetail/tabid/86/rvdsfpid/49950/default.aspx";
url = url.Replace("http://", ""); //get rid of that, add code to check for https?
string[] x = url.Split('/');
string productCode = x[5]; //assuming the product code is always the 6th item in the array!
string code = "";
if (productCode.IndexOf("-") > -1)
{
code = productCode.Substring(productCode.LastIndexOf("-")+1);
}
else
{
code = productCode;
}

convert path into absolute url

I have a part of URL like below:
"employee/employeeDetail.aspx"
And the base path of the whole URL is:
"example.com/siteName"
And the desired output should be:
"http://www.example.com/siteName/employee/employeeDetail.aspx"
I've tried the below:
page.ResolveClientUrl(#"/employee/employeeDetail.aspx");
But the result was
"/employee/employeeDetail.aspx"
Instead of combining the two strings i.e.
string baseURL = #"example.com/siteName";
string relativeURL = #"employee/employeeDetail.aspx";
string finalURL = baseURL + relativeURL;
Are there any other better ways to form a URL?
I've tried adding ~ before the baseURL
page.ResolveClientUrl(#"~/employee/employeeDetail.aspx");
But the outcome was
../employee/employeeDetail.aspx
Generally, it's best to take a look at the incoming request and to build from that...
var ub = new UriBuilder(Request.Url);
var someNewPath = HostingEnvironment.MapPath("~/app/relative/path");
ub.Path = someNewPath;
ub.Query = perhapsAQueryString;
var absoluteUri = ub.Uri;
...but sometimes when you're behind a load-balancer, things might get more complicated, and you have to look at headers added by the load-balancer, such as X-REQUESTED-FOR
You need to tell the method that your url is relative from the application root path by adding the ~ at the beginning:
page.ResolveClientUrl(#"~/employee/employeeDetail.aspx");
If you don't do that, it will be resolved as absolute path from the root of your webserver.
you missed '~' symbol
tilde (~) to indicate the root.
page.ResolveClientUrl(#"~/employee/employeeDetail.aspx");

Categories

Resources