Chris F
Chris F

Reputation: 2946

Should Html.Encode be called when building ActionLinks in ASP.NET MVC

If the name of a link is pulled from the database, should you be calling the Html.Encode method to clean the name?

For example:

Html.ActionLink(Model.PersonFromDB.FirstName,
                "Action",
                "Controller",
                new RouteValueDictionary { { "id", Model.PersonFromDB.Id } },
                null)

or:

Html.ActionLink(Html.Encode(Model.PersonFromDB.FirstName),
                "Action",
                "Controller",
                new RouteValueDictionary { { "id", Model.PersonFromDB.Id } },
                null)

It would make sense that you would want to do this to ensure that there are no dangerous strings injected into the page between <a> and </a> tags, but are scripts and such executable between anchor tags?

Upvotes: 2

Views: 820

Answers (3)

Dan Diplo
Dan Diplo

Reputation: 25339

No, since according to this thread on SO HtmlAction.Link() already HTML encodes values, so you'd end up doing it twice.

Upvotes: 6

Kevin Pang
Kevin Pang

Reputation: 41442

It's certainly a good idea, but you should probably be preventing users from entering in potentially malicious strings as their first name.

Upvotes: 0

casperOne
casperOne

Reputation: 74530

Yes, absolutely. As a general rule, for any HTML that you are going to output that was originally obtained from an untrusted source, assuming the format wasn't HTML already (and sufficiently vetted), you should always HTML encode the string to protect against injection attacks.

Upvotes: -1

Related Questions