Querystring Issue on C# with special characters

自古美人都是妖i 提交于 2020-12-10 00:21:26

问题


I came across a very weird issue where in my querystirng had "++" as part 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();

回答1:


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.




回答2:


You should use UrlEncode and UrlDecode

Those methods should be used any time you're inserting user inputted data into the query string.




回答3:


'+' is reserved in query strings.

Within a query component, the characters ";", "/", "?", ":", "@", "&", "=", "+", ",", and "$" are reserved.

Try using UrlEncode to encode your query strings.




回答4:


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.




回答5:


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);
}



回答6:


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;
    }


来源:https://stackoverflow.com/questions/4380388/querystring-issue-on-c-sharp-with-special-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!