I am trying to get a value from a Encoded URL in C#. So for example, I am trying to get "customerID" from:
http://<DOMAIN>/default.aspx%3FcustomerID%3D12345%26reference%3D2222
I tried the following:
string customerID = HttpUtility.UrlDecode(Request.QueryString["customerID"]);
But it comes back NULL. What is the proper way to get this value??
Thanks
Jay
string str = " http://DOMAIN/default.aspx%3FcustomerID%3D12345%26reference%3D2222";
var url = HttpUtility.UrlDecode(str);
var parameters = HttpUtility.ParseQueryString(new Uri(url).Query);
var id = parameters["customerID"];
your application should be encoding the ? and = signs. The Request variables are setup by iis usually before the information is handed off to the application handling the request. You need to send the should encode values but not the entire url. If your url looked like,
?customerID=1234 I imagine it would work, the problem is not with your code but with how the url is being constructed.
Related
I am unable to get the querystring parameter from url in asp.net
url is:here
My code is
string code = Request.QueryString["code"];
string clientid = Request.QueryString["client_id"];
i am getting code parameter but client_id is null. wt i am doing wrong here.
you are use like,
string code = Request.QueryString["response_type"];
string clientid = Request.QueryString["client_id"];
you are mistake in string code = Request.QueryString["response_type"];
check with this please.
The redirection url is not proper encoded hence during redirection from google the query string parameter after first & in redirect_uri will be ignored (redirect_uri should not contain & as it is you have to keep it in encoded form %26).
The initial url is (contain 'client_id'):
https://accounts.google.com/o/oauth2/auth?scope=profile%20email&state=%2Fprofile&redirect_uri=http://localhost:14772/WebForm2.aspx&response_type=code&client_id=41866849709-lobbqne5v4asm7dn2fu1v8lubm6pc7e7.apps.googleusercontent.com&approval_prompt=force
But after redirected by google its not have Client_Id.
http://localhost:14772/WebForm2.aspx?state=/profile&code=4/gh9Yl3D5Nn220V3nU8d8E5vzC4SmEP6JncnGa6MrgSs#
The issue is redirect_uri content is not encoded correctly. Please configur correctly. It should look like:
http%3A%2F%2Flocalhost%3A14772%2FWebForm2.aspx%26response_type%3Dcode%26client_id%3D41866849709-lobbqne5v4asm7dn2fu1v8lubm6pc7e7.apps.googleusercontent.com%26approval_prompt%3Dforce
I have an s3 bucket called foo.example.com, which is all CNAMEd correctly.
I'm switching to the latest AWS .net SDK.
I wish to generate pre signed url like:
http://foo.example.com/myfile.txt?s3_params_here
Note the vanity cname there.
I have:
string bucketName = "foo.example.com";
AmazonS3Client s3Client = new AmazonS3Client("bar", "xxx",
new AmazonS3Config
{
ServiceURL = bucketName,
CommunicationProtocol = Protocol.HTTP
});
string key = "myfile.txt";
GetPreSignedUrlRequest request = new GetPreSignedUrlRequest()
.WithBucketName(bucketName)
.WithKey(key)
.WithExpires(DateTime.Now.AddMinutes(5))
.WithProtocol(Protocol.HTTP);
string url = s3Client.GetPreSignedURL(request);
the url I get is something like:
http://foo.example.com.foo.example.com/myfile.txt?AWSAccessKeyId=bar&Expires=1331069777&Signature=234KoUUvfE1nCcs2vLj9RQUhqF8%3D
Which is clearly wrong.
I've tried a buch of different variations with ServiceURL, bucketname, etc, but nothing seems to work.
I can't find any good documentation - what is the correct way to do this?
Thanks.
Update [workaround]
I've meanwhile resolved the contradicting test results of mine, which stem from respectively unsystematic testing and URL manipulations. The following workaround does the trick for me (i.e. tested and reproducible), simply starting from your solution:
string bucketName = "foo.example.com";
// [...]
GetPreSignedUrlRequest request = new GetPreSignedUrlRequest()
.WithBucketName(bucketName)
.WithKey(key)
.WithExpires(DateTime.Now.AddMinutes(32))
.WithProtocol(Protocol.HTTP);
Now this yields the erroneous URL with a duplicate domain name, i.e. http://foo.example.com.foo.example.com/myfile.txt?[...]
The duplicate can simply be removed though, e.g.:
string url = s3Client.GetPreSignedURL(request);
// KLUDGE: remove duplicate domain name.
url = url.Replace(bucketName + "." + bucketName, bucketName);
This yields a proper working pre-signed URL for me (i.e. http://foo.example.com/myfile.txt?[...]) by working around the encountered limitation regarding the desired approach outlined below.
Justification
Manipulating the generated URL like so seems odd, but this not having an effect on the query string authentication is in line with how these signatures are created, see Query String Request Authentication Alternative, where you'll find the pseudo-grammar that illustrates the query string request authentication method:
StringToSign = HTTP-VERB + "\n" +
Content-MD5 + "\n" +
Content-Type + "\n" +
Expires + "\n" +
CanonicalizedAmzHeaders +
CanonicalizedResource;
That is, the domain name isn't used for the signature creation at all, rather only information regarding the resource itself; section Example Query String Request Authentication right below the referenced pseudo-grammar fragment illustrates this with an actual resource.
Assessment
I don't know whether there is still a misunderstanding on our part or whether this might just be a bug in the AWS SDK for .NET, see e.g. Why is my S3 pre-signed request invalid when I set a response header override that contains a “+”? for a related bug resolved via a similar workaround as well, which has meanwhile been fixed though; accordingly, this should likely be escalated to the AWS forums and/or support channels to get an appropriate answer or solution.
Good luck!
Desired answer [dysfunctional]
The S3 CNAME handling implies the bucket name already, so all you need to do is removing your bucket name from GetPreSignedUrlRequest, i.e. it should look like so:
GetPreSignedUrlRequest request = new GetPreSignedUrlRequest()
.WithKey(key)
.WithExpires(DateTime.Now.AddMinutes(5))
.WithProtocol(Protocol.HTTP);
I've tested this with a bucket of mine and it works as expected like so.
the presignedURL returns an URL object after signing the request. I have used the same and >dont have real issues, but there are some things to consider:
Ensure the object URL you are considering does not have a '//' it could easily happen if >you start the storage path starts with a "/", you would have stored the object in a path some >thing like https:///x/y/z/abc.png the key for such a resource is x/y/z/abc.png >and not /x/y/z/abc.png
If the above is ensured, then from the URL object that is returned get the query parameters >from the URL object url.getQuery() will return the query parameters which contains the >signature information, just suffix this with your original awsURL and things should work with >out any encoding issues.
Hope this helps..
Essentially you need to use url.getQuery on the returned url object rather than simply affixing it to the end of your bucket.
https://forums.aws.amazon.com/thread.jspa?threadID=70521
I have a url with querystring http://www.sample.com?q=asdasdsdasd . Will it be possible to modify the querystring so that I could replace it with /myaccount i.e at the end the url will look like http://www.sample.com/myaccount.
string destUrl = string.Format("{0}://{1}{2}/",Request.Url.Scheme,Request.Url.Authority,Request.Url.AbsolutePath);
if (destUrl.EndsWith("/"))
destUrl = destUrl.TrimEnd(new char[] { '/' });
if (!string.IsNullOrEmpty(Request.QueryString["paramName"])) {
destUrl = string.Format("{0}?paramName={1}", destUrl, "paramValueHere");
Response.Redirect(destUrl);
Check out url rewriting. You may not be able to achieve the /myaccount direct, but you can tidy up your urls, make them more readable and meaningful for SEO.
You will be able to use to allow your url to look similar to the following :
www.sample.com/account/asdaasdasd
If you lose the query string all together you won't be able to access it at all. Unless you implemented some form of interim code that will get the query string, store it in a session and then redirect to your /myaccount url and get it back there.
I think you are referring to URL Rewriting.
This is quite a commonly used blog post regarding URL rewriting:
http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx
Or if you have IIS7, its now been made easier:
http://www.iis.net/download/urlrewrite
In terms of changing ?q=asdasdsdasd to /myaccount though, I don't understand. The first URL seems like a typical search query, and the second is a URL which would probably use cookies etc to pick up the variables (as its for a user account?).
But URL Rewriting can be used so that if you have a user profile with a URL like:
www.sample.com?userprofile.aspx?user=johnsmith
This can be rewritten, using the johnsmith part as a variable like:
www.sample.com/user/johnsmith
With simple string manipulation you could do it as:
string urlWithQuerystring = "http://www.sample.com?q=asdasdsdasd";
int queryStringPos = urlWithQuerystring.IndexOf("?");
string newUrl = String.Format("{0}/myaccount/", urlWithQuerystring.Substring(0, queryStringPos));
Use the this Code in your Global.asax:
void Application_BeginRequest(object sender, EventArgs e)
{
string[] parts = Request.RawUrl.Split(new char[]{'/'});
if(Part[1] == "myaccount"))
Context.RewritePath("http://www.sample.com?q=" + Part[2]);
}
and then use this address
http://www.sample.com/myaccount/asdasdasd
I have a URL and data is being posted on that URL through ERP software from another vendor.....I want to collect the data posted on my URL in page load event from that vendor....What should be done for that in ASP.NET with c#?
He does not have a field name and he is auto-generating the string of data and then posting it automatically to my ASP.NET page.
First if you know what kind of data you're going to receive then you should add:
Page.Response.ContentType = "text/xml"; //For XML Data
Then read that data in stream reader:
StreamReader sr = new StreamReader(Page.Request.InputStream);
The data in streamreader is Url Encoded. So you've to decode it before you use that further:
string main = Server.UrlDecode(sr.ReadToEnd());
That's all. I hope it helps.
var parameter = Request.QueryString["parameterName"];
if (parameter != null)
{
//.. use it
}
See HttpRequest.QueryString
I understand you said that the Query doesn't have a field name; meaning you can't look for it like a normal QueryString, using the string indexer. If so, then you probably have to access it without knowing the query key.
assuming you know that the 'data' is the first parameter, you could access it like this:
string data = Request.QueryString.getKey(0);
If that won't work, you can access the url directly
string query = Request.Url.Query;
If they are doing a POST, you can use Request.Form. It will return a NameValueCollection of the elements posted to the Url, and you can loop through it if you don't know the name of what is being posted. If you know the name, then you can do Request.Form["NamedItem"].
foreach(var key in Request)
{
var data = Request[key];
}
will iterate through Request.Querystrung, Request.Form, and Request.Params.
I would like to take the original URL, truncate the query string parameters, and return a cleaned up version of the URL. I would like it to occur across the whole application, so performing through the global.asax would be ideal. Also, I think a 301 redirect would be in order as well.
ie.
in: www.website.com/default.aspx?utm_source=twitter&utm_medium=social-media
out: www.website.com/default.aspx
What would be the best way to achieve this?
System.Uri is your friend here. This has many helpful utilities on it, but the one you want is GetLeftPart:
string url = "http://www.website.com/default.aspx?utm_source=twitter&utm_medium=social-media";
Uri uri = new Uri(url);
Console.WriteLine(uri.GetLeftPart(UriPartial.Path));
This gives the output: http://www.website.com/default.aspx
[The Uri class does require the protocol, http://, to be specified]
GetLeftPart basicallys says "get the left part of the uri up to and including the part I specify". This can be Scheme (just the http:// bit), Authority (the www.website.com part), Path (the /default.aspx) or Query (the querystring).
Assuming you are on an aspx web page, you can then use Response.Redirect(newUrl) to redirect the caller.
Here is a simple trick
Dim uri = New Uri(Request.Url.AbsoluteUri)
dim reqURL = uri.GetLeftPart(UriPartial.Path)
Here is a quick way of getting the root path sans the full path and query.
string path = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery,"");
This may look a little better.
string rawUrl = String.Concat(this.GetApplicationUrl(), Request.RawUrl);
if (rawUrl.Contains("/post/"))
{
bool hasQueryStrings = Request.QueryString.Keys.Count > 1;
if (hasQueryStrings)
{
Uri uri = new Uri(rawUrl);
rawUrl = uri.GetLeftPart(UriPartial.Path);
HtmlLink canonical = new HtmlLink();
canonical.Href = rawUrl;
canonical.Attributes["rel"] = "canonical";
Page.Header.Controls.Add(canonical);
}
}
Followed by a function to properly fetch the application URL.
Works perfectly.
I'm guessing that you want to do this because you want your users to see pretty looking URLs. The only way to get the client to "change" the URL in its address bar is to send it to a new location - i.e. you need to redirect them.
Are the query string parameters going to affect the output of your page? If so, you'll have to look at how to maintain state between requests (session variables, cookies, etc.) because your query string parameters will be lost as soon as you redirect to a page without them.
There are a few ways you can do this globally (in order of preference):
If you have direct control over your server environment then a configurable server module like ISAPI_ReWrite or IIS 7.0 URL Rewrite Module is a great approach.
A custom IHttpModule is a nice, reusable roll-your-own approach.
You can also do this in the global.asax as you suggest
You should only use the 301 response code if the resource has indeed moved permanently. Again, this depends on whether your application needs to use the query string parameters. If you use a permanent redirect a browser (that respects the 301 response code) will skip loading a URL like .../default.aspx?utm_source=twitter&utm_medium=social-media and load .../default.aspx - you'll never even know about the query string parameters.
Finally, you can use POST method requests. This gives you clean URLs and lets you pass parameters in, but will only work with <form> elements or requests you create using JavaScript.
Take a look at the UriBuilder class. You can create one with a url string, and the object will then parse this url and let you access just the elements you desire.
After completing whatever processing you need to do on the query string, just split the url on the question mark:
Dim _CleanUrl as String = Request.Url.AbsoluteUri.Split("?")(0)
Response.Redirect(_CleanUrl)
Granted, my solution is in VB.NET, but I'd imagine that it could be ported over pretty easily. And since we are only looking for the first element of the split, it even "fails" gracefully when there is no querystring.