How to protect against XSS in ASP.NET Core?

You can use the HtmlSanitizer NuGet package in ASP.NET Core.


Specifically, what are you trying to do here? Prevent posts which could contain content which could render, when un-sanitised an XSS attack? If so, as I recently discussed with a colleague, you kind of can't, depending on your site.

You can provide client-side restrictions on the data posted, but this can obviously be bypassed, so what's your action trying to do? Prevent content being posted that when rendered un-sanitised is a potential XSS risk?

What is your post endpoint responsible for? Is it responsible for how other systems may render some output it has received?

I would argue your main XSS risk is in how an app renders your data. If you're not sanitising/encoding output based on the app that is using the data then you're probably doing it wrong.

Remember that a potential XSS issue is only a real issue if you're outputting something to a webpage or similar. This is not really the endpoint that receives the data's problem.


I know this is a year old now, but for your (and others') reference, you may want to look at creating a ResourceFilter or Middleware which will sanitize incoming requests. You can use whatever tools or custom code you want there, but the key being that all incoming requests go through this filter to be sanitized of bad data.

Be sure to use the correct filter for your application/need. A ResourceFilter will run before model binding, and an ActionFilter will run after model binding.


One of the best ways in preventing stored/reflected XSS is to HTML-Encode the output. You may also encode before you store it in the DB. Since you don't need the output from these fields to be in HTML anyways.

The solution with the Regex won't always work. What you're doing here is that you are relying on a blacklist. It's always better and more secure to either rely on Whitelist (Which you don't need in this case). Or HTML-Encode the output if possible.