mercredi 15 février 2017

ASP.Net - Return user control html\text as escaped

This is a twist on the typical question of: 'How to Get the HTML of a User Control?' I know how to do this and I have been doing it for years but recently I became more knowledgeable about web security and I noticed that my string (aka Control HTML) is being return to the client as normal HTML and it is not encoded\escaped. I know that I can escape it once it gets to the browser using javascript but it would be more secure if it came from the server already escaped.

Currently I am getting something back to the client like:

returnText = "<input id='myButton' text='whatever'>"

What I am looking for is:

returnText = "&lt;input%20id='myButton'%20text='whatever'&gt;"

(or something similar)

The code I am using is very typical for these types of calls. My ASCX Response is coded as:

StringBuilder myStringBuilder = new StringBuilder();
TextWriter myTextWriter = new StringWriter(myStringBuilder);
HtmlTextWriter myWriter = new HtmlTextWriter(myTextWriter);
viewControl.RenderControl(myWriter);
strControl = myTextWriter.ToString();

And I am calling my control on the server using the XMLHTTPRequest object:

function callServer(strPage,qryParms) {
if (xmlHttp != null) { xmlHttp.abort(); }
xmlHttp = null;
var retValue = "";
xmlHttp = CreateHttpRequest();
if (xmlHttp == null) {
    alert("Your browser does not support Ajax HTTP Requests");
    return;
}
else {
    xmlHttp.open("POST", strPage, false);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.onreadystatechange = function () 
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            retValue = xmlHttp.responseText;
        }
    }
    xmlHttp.send(qryParms);
}
// retValue = htmlEncode(retValue);  <--- this is where I could convert it.
return retValue;
}

Can I somehow intercept the Response object during the Render process to escape the string before it comes back to the browser?

Thanks!

Aucun commentaire:

Enregistrer un commentaire