How can I stop asp.net encoding & in Get params?

2019-07-11 19:37发布

问题:

I am using the following code to add a series of calls to the body parameter of a page in asp.net:

uxBodyTag.Attributes["onbeforeunload"] += 
  "ajaxRequest('UnlockQuery.ashx?QueryID=" + queryId.ToString() + 
  "&UserID=" + Session["UserID"].ToString() + "');";

This is being rendered as:

<body id="uxBodyTag" onbeforeunload=
    "ajaxRequest('UnlockQuery.ashx?QueryID=176&amp;UserID=11648');">

The &amp; means my ashx page is not retrieving the correct variables - how can I stop asp.net from doing this?

EDIT:

Using Server.UrlEncode gives me the following:

<body id="uxBodyTag" onbeforeunload=
 "ajaxRequest('UnlockQuery.ashx%3fQueryID%3d179%26UserID%3d11648')%3b">

Which is far worse.

回答1:

In HTML the ampersand needs to be encoded, always, everywhere, also in attribute values (the contents of the <script> tag is the notable exception, obviously). ASP.NET does the right thing.

Attribute values will be unencoded by the browser before it actually uses them. So your onbeforeunload attribute has a literal value of:

ajaxRequest('UnlockQuery.ashx?QueryID=176&UserID=11648');

while the HTML representation needs to have the &amp; in place of the &. The browser usually understands the ill-encoded version as well, but an SGML parser would complain about an unknown/invalid entity named &UserID.



回答2:

The behaviour you are seeing with & encoded as &amp; is the behaviour you want. By the time the text gets to your ajaxRequest function it will have been unencoded again and everything should be fine.