61 lines
1.4 KiB
Plaintext

=== How to fix it in ASP.NET
[cols="a"]
|===
h| Non-compliant code example
|
[source,csharp]
----
using System.Web;
using System.Web.Mvc;
public class HelloController : Controller
{
[HttpGet]
public void Hello(string name, HttpResponse response)
{
string html = "<h1>Hello"+ name +"</h1>"
response.Write(html);
}
}
----
h| Compliant solution
|
[source,csharp]
----
using System.Web;
using System.Web.Mvc;
public class HelloController : Controller
{
[HttpGet]
public void Hello(string name, HttpResponse response)
{
string html = "<h1>Hello"+ HttpUtility.HtmlEncode(name) +"</h1>"
response.Write(html);
}
}
----
|===
=== How does this work?
If the HTTP response is HTML code, it is highly recommended to use https://docs.microsoft.com/en-us/aspnet/web-pages/overview/getting-started/introducing-razor-syntax-c[Razor-based view templates] to generate it.
This template engine separates the view from the business logic and automatically encodes the output of variables, drastically reducing the risk of cross-site scripting vulnerabilities.
include::../../common/fix/data_encoding.adoc[]
`System.Web.HttpUtility.HtmlEncode` is the recommended method to encode HTML entities.
=== Pitfalls
include::../../common/pitfalls/validation.adoc[]
=== Going the extra mile
include::../../common/extra-mile/csp.adoc[]