Search code examples
c#request.querystring

Using Request.QueryString, slash (/) is added to the last querystring when it exists in the first querystring


this is my first post on stackoverlow and I couldn't find a solution to this in any other posts, so here it goes:

I have a web page that is sending two query strings in the url:

example.aspx?name=<%=name%>&sku=<%=sku%>

I then collect the values using Request.QueryString["name"]; and Request.QueryString["sku"];

When I view the url on the source of the page sending the query strings everything looks fine, but if "name" contains a forward slash (/) it will somehow get tacked on to the end of "sku" when I retrieve the value of the query string. I've tried to replace the / with %2F but that doesn't work. If the "name" query string doesn't have a slash everything looks correct.

Any Ideas?

Edit: I ended up having to double encode (server.urlencode) and double decode for it to work correctly. Thanks for all your help!


Solution

  • Actually, your should encode your values for URLs with HttpServerUtility.UrlEncode method:

    example.aspx?name=<%=Server.UrlEncode(name)%>&sku=<%=Server.UrlEncode(sku)%>
    

    URL encoding ensures that all browsers will correctly transmit text in URL strings. Characters such as a question mark (?), ampersand (&), slash mark (/), and spaces might be truncated or corrupted by some browsers. As a result, these characters must be encoded in tags or in query strings where the strings can be re-sent by a browser in a request string.

    EDIT:

    let's check this with the values you provided: name = Bellagio™ 16 1/2" High Downbridge Outdoor Wall Light, sku = 46910: firstly I created a page with 2 properties:

    public string Name
    {
        get
        {
            return "Bellagio™ 16 1/2\" High Downbridge Outdoor Wall Light";
        }
    }
    
    public string Sku
    {
        get
        {
            return "46910";
        }
    }
    

    and then add link definition to the page:

    <a href='1.aspx?name=<%=Server.UrlEncode(Name)%>&sku=<%=Server.UrlEncode(Sku)%>'>
        this is a link
    </a>
    

    and then grab these values (click the link firstly):

    protected void Page_Load(object sender, EventArgs e)
    {
        var name = Request.QueryString["name"];
        var sku = Request.QueryString["sku"];
    }
    

    these values are exactly the same as you provided: Bellagio™ 16 1/2\" High Downbridge Outdoor Wall Light and 46910.

    Unfortunatelly, I was unable to reproduce an incorrect URL you post in your first comment: LifeSizePDF.aspx?productname=Bellagio&amp;%238482%3b+16+1%2f2&amp;quot%3­b+High+Downbridge+Outdoor+Wall+Light&amp;shortsku=46910%2f