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
Related
I need to apply the following transformation to a string:
convert the string in byte[]
apply the sha256 function
encode the result in base64
I wrote the following code:
string codeRaw = "C0643778W.EUC06AG978W.EUFWELP2014-11-2153.50000GBP24.00000MWh/h10YCB-EUROPEU--12015-01-012015-01-31";
byte[] utiCodeByteArr = Encoding.UTF8.GetBytes(codeRaw);
byte[] hashByteArr = new SHA256Managed().ComputeHash(utiCodeByteArr);
string hash = Convert.ToBase64String(hashByteArr)
It works, but the result is a little bit different from was I should get: the string contains the chars '+', '/' and '=' instead of 'A', 'B' and 'C'.
"qWAIh1CgYAuvoRTGcvXKLBHC9UxRunSBRjRXlqhYh6gC" //expected result
"qW+Ih1CgYAuvoRTGcvXKLBHC9UxRunS/RjRXlqhYh6g=" //got result
I've solved with a replace
string hash = Convert.ToBase64String(hashByteArr)?.Replace("+", "A")?.Replace("/", "B")?.Replace("=", "C");
There is a better way to get the right string without using the replaces?
I don't like them.
The manual with the requirements say: "The APIs used are the ones provided by .NET framework", but it doesn't contains the source code: maybe there is a way to get immediately the ABC chars, but I miss it.
Thanks.
The provider sent me the source code: there was a replace as the one I did.
They forgot to wrote that information in the manual.
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 tried with WebUtility.UrlEncode and Uri.UnescapeDataString but it is encoding the whole url but i want only the gap(space) to fill with %20. My code is below.
string url = "https://www.example.com/images/catalog/operators/Ajmer Vidyut Vitran Nigam.png";
//Method1
string imageUrl = WebUtility.UrlEncode(url);
//Method2
string temp = Uri.EscapeDataString(url);
Actual url after encoding: "https%3A%2F%2Fassetscdn.paytm.com%2Fimages%2Fcatalog%2Foperators%2FAjmer+Vidyut+Vitran+Nigam.png"
Expected url:
"https://assetscdn.paytm.com/images/catalog/operators/Ajmer%20Vidyut%20Vitran%20Nigam.png"
Thanks in advance :)
Use Uri.EscapeUriString
string imageUrl = Uri.EscapeUriString(url);
You can use HttpUtility.UrlPathEncode Method (String). Check more info here
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]))));
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>