Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html encoding in MVC input

I'm working through NerdDinner and I'm a bit confused about the following section...

First they've added a form for creating a new dinner, with a bunch of textboxes delcared like:

<%= Html.TextArea("Description") %>

They then show two ways of binding form input to the model:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create() {
    Dinner dinner = new Dinner();
    UpdateModel(dinner);
    ...
}

or:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Dinner dinner) { ... }

Ok, great, that all looks really easy so far.

Then a bit later on they say:

It is important to always be paranoid about security when accepting any user input, and this is also true when binding objects to form input. You should be careful to always HTML encode any user-entered values to avoid HTML and JavaScript injection attacks

Huh? MVC is managing the data binding for us. Where/how are you supposed to do the HTML encoding?

like image 696
fearofawhackplanet Avatar asked May 25 '10 17:05

fearofawhackplanet


People also ask

What is HTML encoding in MVC?

In ASP.NET Web Forms we have a couple of ways to do HTML encoding: ASP.NET 3.5 and below: <%= Html.Encode(data to encode) %> ASP.NET 4: <%: data to encode %> The above approaches help us in mitigating Cross Site Scripting (XSS) attacks in ASP.NET Web Forms. ASP.NET MVC Razor expressions are automatically HTML encoded.

Why we use HTML raw in MVC?

I use the Html. Raw to print a raw html content, for example when I send some thing like ViewBag. div = "<div> Hello </div>"; from the controller to the view side it does not print a raw html content unless I use the Html.

What is HtmlEncode C#?

HtmlEncode(String) Converts a string to an HTML-encoded string. HtmlEncode(String, TextWriter) Converts a string into an HTML-encoded string, and returns the output as a TextWriter stream of output.


1 Answers

You generally (but not always) want to HTML encode the values before writing them out, typically in your views, but possibly from the controller as well.

Some info here: http://weblogs.asp.net/scottgu/archive/2010/04/06/new-lt-gt-syntax-for-html-encoding-output-in-asp-net-4-and-asp-net-mvc-2.aspx

like image 65
D'Arcy Rittich Avatar answered Oct 20 '22 15:10

D'Arcy Rittich