3

I need to be able to handle an HTML encoded ampersand in my .Net code.

So the Url is

http://myite.com/index.aspx?language=en&Refresh=true

There is no way of changing this as it has been generated by something else so this is out of my control.

How can I read the Refresh parameter?

I have tried

HttpUtility.UrlDecode(Request.QueryString("Refresh")) 

but my Request.QueryString("Refresh") is actually empty, so this is pointless, as is Uri.EscapeDataString.

This can't be the first time this has happened, but I'm struggling to find a solution, as most people would say use UrlEncoding, but as I said, the Url is out of my control.

Stuart Dobson
  • 3,001
  • 4
  • 35
  • 37

2 Answers2

6

& in your query string should be %26.

Since you can't correct the url.

You can read the refresh value as:

Request.QueryString("amp;Refresh");

Note that the developer of the service you are using may correct this in future. It would be good to be ready for that already.

var refresh = Request.QueryString("amp;Refresh");
if(String.IsNullOrEmpty(refresh))
    refresh = Request.QueryString("Refresh");
nunespascal
  • 17,584
  • 2
  • 43
  • 46
  • So simple! I don't know why I didn't think of it – Stuart Dobson Aug 30 '12 at 00:23
  • 1
    I don't think the %26 is the right solution for his example, that will allow you to encode an "&" symbol into your parameter value, I.e., so you can have a parameter such as "?name=bob&jill" by doing "?name=bob%26jill". The url should have an "&" symbol separating the parameters in the first place. Good solution for him using the "amp;Refresh" though! – Justin Clarke Jun 03 '14 at 11:27
0

nunespascal answer pretty much solves your problem. There are some alternate methods.

If its guaranteed that your Refresh parameter is the second key in the QueryStringCollection then you can use Request.QueryString(1)

Another method is to do a Contains on the QueryStringCollection.

If Request.QueryString IsNot Nothing AndAlso Request.QueryString.AllKeys.Count() > 0 Then
    Dim refreshKey = Request.QueryString.AllKeys.FirstOrDefault(Function(nv) nv.Contains("Refresh"))
    If refreshKey IsNot Nothing Then
        Dim refreshValue = Request.QueryString(refreshKey)
    End If
End If
naveen
  • 53,448
  • 46
  • 161
  • 251