Querystring Issue on C# with special characters
I came across a very weird issue where in my querystirng had "++" as part开发者_JAVA技巧 of the text. but when i assign the query stirng value to a string ++ will become two spaces. How do i get exactly what is being passed as querystring?
I observed that the querystirng collection had "++" but when I do Request.QueryString["search"].ToString() "++" gone, I checked in Immediate window.
I use C# 2.0
URL: /default.aspx?search=test++
string t = Request.QueryString["search"].ToString();
You should use UrlEncode and UrlDecode
Those methods should be used any time you're inserting user inputted data into the query string.
'+' is reserved in query strings.
Within a query component, the characters ";", "/", "?", ":", "@", "&", "=", "+", ",", and "$" are reserved.
Try using UrlEncode to encode your query strings.
A plus sign in a query string translates to a space. If you want an actual plus sign rather than a space, use %2B
instead.
/default.aspx?search=test%2B%2B
If you're doing this in code, then you should be using UrlEncode
to encode this portion of the query string.
I don't know that there's a way to get the exact text passed into the query. The HTTP standards basically say that a +
is equivalent to a space character, so if you want to preserve the +
you should encode the query string, as Chuck said.
The only solution I found was in this post HERE:
private string GetQueryStringValueFromRawUrl(string queryStringKey)
{
var currentUri = new Uri(HttpContext.Request.Url.Scheme + "://" +
HttpContext.Request.Url.Authority +
HttpContext.Request.RawUrl);
var queryStringCollection = HttpUtility.ParseQueryString((currentUri).Query);
return queryStringCollection.Get(queryStringKey);
}
Working on a ASP.Net 2.0 soluton, I had to do the following:
private string GetParameterFromRawUrl(string parameter)
{
var rawUrl = Request.RawUrl;
int indexOfParam = rawUrl.IndexOf(parameter);
int indexOfNextParam = rawUrl.IndexOf('&', indexOfParam);
string result;
if (indexOfNextParam < 1)
{
result = rawUrl.Substring(indexOfParam);
}
else
{
result = rawUrl.Substring(indexOfParam, (indexOfNextParam-indexOfParam));
}
return result;
}
精彩评论