I want to use a console application to easily divide a URL from its params so I can URL encode the parameters. Is there a type that makes this simple? Please keep in mind that this is being run outside of a web server.
The URL is of the form
E.G.
string url = "http://sitename/folder1/someweb.dll?RetrieveTestByDateTime?PatientID=1234¶m2=blah blah blah";
So then I can do
string finalUrl = "http://sitename/folder1/someweb.dll?RetriveTestByDateTime?PatientID=" + HttpUtility.UrlEncode(PatientIDValue) + HttpUtility.UrlEncode(param2Value);
Second, is the second ? valid? This data comes from a 3rd party app. Surely this can be accomplished with Regex, but I prefer not to use it as most people on my team do not know regular expressions.
Use the Uri class - pass in the string url to the constructor and it will parse out the different parts.
The query will be in the Query property and you can reconstruct the URL easily using the Scheme, AbsolutePath and the encoded Query.
Firstly your url structure is bad
string url = "http://sitename/folder1/someweb.dll?RetrieveTestByDateTime?PatientID=1234¶m2=blah blah blah";
should be
string url = "http://sitename/folder1/someweb.dll?RetrieveTestByDateTime&PatientID=1234¶m2=blah blah blah";
A possible solution, I'm not in a development environment now so this is from the head. Some changes may need to be done to the code.
string url = "http://sitename/folder1/someweb.dll?RetrieveTestByDateTime&PatientID=1234¶m2=blah blah blah";
var uri = new Uri(url);
var queryString = uri.Query;
NameValueCollection query = HttpUtility.ParseQueryString(queryString)
query["PatientID"] = string.Concat(HttpUtility.UrlEncode(PatientIDValue), HttpUtility.UrlEncode(param2Value));
// Rebuild the querystring
queryString = "?" +
string.Join("&",
Array.ConvertAll(query.AllKeys,
key => string.Format("{0}={1}",
HttpUtility.UrlEncode(key),
HttpUtility.UrlEncode(query[key]))));
Related
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();
I have a url string that I want to encode before passing it as an argument to the browser. I'm used the "HttpUtility.UrlEncode" function but found out that it doesn't encode all the URL, it doesn't take the query param.
For Example:
string url = "http://www.google.com?A --chrome-frame"
This function will not encode the space char after the parameter.
The "Uri.EscapeUriString" will encode the spacing but will it encode all other character that the "UrlEncode" function encode?,
Note that I can't use them both because this will break the URL.
Does:
string encodeUrl = Uri.EscapeUriString(url);
Is equivalent to:
Uri uriObject = new Uri(url);
string encodeUrl = uriObject.AbsoluteUri;
Do you have other suggestions?
*Note that its not duplicate of "Server.UrlEncode vs. HttpUtility.UrlEncode" :)
Thanks
This is my url which contains 4 querystrings(desc,url,img,title).
http://localhost:4385/Default?desc=Home%20Page&url=http://localhost:4385/&img=http://localhost:4385/images/ribbon-img.png&title=
I read querystrings like below,
string title = Request.QueryString["desc"];
string pageurl = Request.QueryString["url"];
string alttext = Request.QueryString["title"];
string imageurl = Request.QueryString["img"];
The output i get is:
title=Home Page&url=http://localhost:4385/&img=http://localhost:4385/images/ribbon-img.png&title="
it takes entire url to first querstring, this is not my expected output.
I expect values to all querystring variables
can anyone please help me
The URL format is incorrect i feel, because the slash / character will be sent as %2F in the query string but that was not done in your URL format.
Update:
Respose.Redirect("http://localhost:4385/Default?desc=Home%20Page&url="+Uri.EscapeDataString("http://localhost:4385/")+"&img="+Uri.EscapeDataString("http://localhost:4385/images/ribbon-img.png")+"&title=");
The problem is that you are not creating the QueryString with proper encoding. .NET framework has HttpUtility.ParseQueryString Method to simplify this problem of encoding. Try this code
//are you sure your URL doesn't have an ".aspx" extension?
var url = " http://localhost:4385/Default.aspx?";
var queryString = System.Web.HttpUtility.ParseQueryString(string.Empty);
queryString["desc"] = "Home Page";
queryString["url"] = "http://localhost:4385/";
queryString["image"] = "http://localhost:4385/images/ribbon-img.png";
queryString["title"] = "";
Response.Redirect(url + queryString.ToString());
Now the QueryString will look like this.
var urlWithQueryString = " http://localhost:4385/Default.aspx?desc=Home+Page&url=http%3a%2f%2flocalhost%3a4385%2f&image=http%3a%2f%2flocalhost%3a4385%2fimages%2fribbon-img.png&title="
Now parsing can be done using the method you tried
string title = Request.QueryString["desc"];
string pageurl = Request.QueryString["url"];
string alttext = Request.QueryString["title"];
string imageurl = Request.QueryString["image"]; //you have wrongly typed "img" here
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");
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>