-2
  string myContent="Hello"
  System.Web.UI.Webcontrols.Literal literal1=new System.Web.UI.Webcontrols.Literal();
  literal1.Text="<b>" + myContent + "</b><table><tr><td>HI</td></tr></table>" ;

But here I am in a situation where I must perform encoding on literal control text value (The reason is to prevent the literal control from XSS attack.). I am using asp.net c#.

So what I did is,

literal1.Text= AntiXssEncoder.HtmlEconde("<b>" + myContent + "</b><table><tr><td>HI</td></tr></table>");

So the output would be,

<b>Hello</b><table><tr><td>HI</td></tr></table>

I don't want the above output(plain text of my markupt) when I do encoding. I want it to render as

Hello
"HI-> should have been printed inside a html tag "

Also I know that the result of the literal control will be just a plain text If I do encoding on the literal control. I want to encode the literal control plus I don't want my literal control's text to render as a plain text. any help would be appreciable.

  • What is the `Type` of `literal1`? – mjwills Jul 06 '18 at 09:05
  • Can you give us a complete example? What is the actual problem you are facing? – Esko Jul 06 '18 at 09:08
  • Please update your example with the actual problem and with expected output and what is the "wrong" output you are getting now? – Esko Jul 06 '18 at 09:18
  • 1
    This question's definition has shifted twice. Please close this question and raise a new one called 'how to avoid xss using asp literal'. – Davesoft Jul 06 '18 at 10:14
  • @Davesoft That is true, there was nothing in the original question about xss. – Esko Jul 06 '18 at 10:17

2 Answers2

1

Answer to your initial question: To prevent XSS insert the text into a Label and add that to a HtmlGenericControl of type "b" to sourround it with a bold-tag like this:

HtmlGenericControl bold = new HtmlGenericControl("b");
Label myContent = new Label();
myContent.Text = "Hello and some special characters <>";
bold.Controls.add(myContent);

The Label-Control will encode every special character inside, which should prevent any XSS attack.

For the new table-part of your question: I suggest not to construct your whole DOM inside of a Literal. That is pretty bad style and should only be used, if there's no other way. Use the available classes (i.e. Table) in the API of ASP.NET instead.

species
  • 36
  • 1
  • 7
0

You could simply do:

literal1.Text= "<b>" + HttpUtility.HtmlEncode(myContent) + "</b>";

Or better yet, use label-control add css-class to it with font-weight: bold;

Esko
  • 4,109
  • 2
  • 22
  • 37