.NET Core 6- HtmlEncode response string through global declaration

572 Views Asked by At

While returning Json Response from .NET Core 6 Web APIs, I want to encode all strings with WebUtility.HtmlEncode. As of now, I am writing this line for each string and I just came across this link: https://stackoverflow.com/a/44117929/3234665.

Is there anyway we can declare this at some central/ global level (i.e. Attribute, Program.cs etc?) to reduce repetitive lines everywhere?

1

There are 1 best solutions below

6
Rena On

For globally add the custom ContractResolver,you need add the configuration in your Program.cs like below :

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews().AddNewtonsoftJson();

//add this service to container...
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
    ContractResolver = new CustomResolver(),
    Formatting= Formatting.Indented,
    DefaultValueHandling= DefaultValueHandling.Ignore,  //add this
};