Extracting the full querystring from a URL - c#

Using ASP.NET MVC, I have the following URL returned from a commeweb payment gateway:
http://localhost/ASP_VPC_3Party_DR?&vpc_AVSResultCode=Unsupported&vpc_AcqAVSRe
spCode=Unsupported&vpc_AcqCSCRespCode=Unsupported&vpc_AcqResponseCode=00&vpc_
Amount=100&vpc_AuthorizeId=000281&vpc_BatchNo=1&vpc_CSCRequestCode=N&vpc_CSCRe
sultCode=Unsupported&vpc_Card=AE&vpc_Command=pay&vpc_Locale=en_AU&vpc_MerchTxn
Ref=123&vpc_Merchant=TESTANDREWK&vpc_Message=Approved&vpc_OrderInfo=VPC+Exam
ple&vpc_ReceiptNo=030821000281&vpc_SecureHash=6EB600780CAA5B1C81BF3AF249E4B85
3&vpc_TransactionNo=281&vpc_TxnResponseCode=0&vpc_Version=1
I need to store this:
&vpc_AVSResultCode=Unsupported&vpc_AcqAVSRe
spCode=Unsupported&vpc_AcqCSCRespCode=Unsupported&vpc_AcqResponseCode=00&vpc_
Amount=100&vpc_AuthorizeId=000281&vpc_BatchNo=1&vpc_CSCRequestCode=N&vpc_CSCRe
sultCode=Unsupported&vpc_Card=AE&vpc_Command=pay&vpc_Locale=en_AU&vpc_MerchTxn
Ref=123&vpc_Merchant=TESTANDREWK&vpc_Message=Approved&vpc_OrderInfo=VPC+Exam
ple&vpc_ReceiptNo=030821000281&vpc_SecureHash=6EB600780CAA5B1C81BF3AF249E4B85
3&vpc_TransactionNo=281&vpc_TxnResponseCode=0&vpc_Version=1
... as a single variable in my database

You ask about full url , but what you need is the query_string.
Full url: Request.Url.AbsoluteUri
Query string: Request.Url.Query

You can get full url.
Request.Url.PathAndQuery
then parse string str.Substring(str.IndexOf('&'))
it gets whole string from starting of &

Related

unable to get the query string parameter in asp.net

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

Get value from Encoded Url

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.

Querystring as part of url

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

rename url content

when url= http://www.iranfairco.com/MainPP.aspx?idCompany=142707090021 .
change content MainPP.aspx by idCompany
for example idCompany=142707090021 equal companyName microsoft
no how can when user enter url: http://www.iranfairco.com/microsoft this equal above url
how can http://www.iranfairco.com/MainPP.aspx?idCompany=142707090021====url:http://www.iranfairco.com/microsoft
You should use some url rewrite module (or write your own - it's not hard).
For example: IIS URL Rewrite, also look here.
Look at also this thourough explanation of how URL Rewriting in ASP.NET works.

Truncating Query String & Returning Clean URL C# ASP.net

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.

Categories

Resources