0

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?

Jeeten Parmar
  • 5,568
  • 15
  • 62
  • 111
  • All Web Api end points you want to return HTML Encoded strings? If so, you can create a custom middleware provider: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/write?view=aspnetcore-7.0 – jon.r Jan 04 '23 at 17:27

1 Answers1

0

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
};
Rena
  • 30,832
  • 6
  • 37
  • 72
  • Do I need to add `JsonConvert` lines directly in `Program.cs` file? – Jeeten Parmar Jan 05 '23 at 09:58
  • Hi, do you mean you also don't want to use `JsonConvert.SerializeObject` every time? You can only globally setting the serialization settings. Serialize or not only can be controlled by JsonConvert. – Rena Jan 05 '23 at 10:10
  • You are right. I am returning a response directly. I have below code in `Program.cs`. `services.AddControllers() .AddJsonOptions(x => x.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull);` – Jeeten Parmar Jan 05 '23 at 10:11
  • Hi, DefaultIgnoreCondition cannot work fine by `AddJsonOptions` in your code, you need set like what my answer did by using the `DefaultValueHandling`. PLs check. – Rena Jan 05 '23 at 10:17
  • Still do I need to use `JsonConvert.SerializeObject` after that line? – Jeeten Parmar Jan 05 '23 at 10:19
  • Yes. of course you need. As my first comment said, you can only globally set the serialization settings, but cannot control the serialization itself. – Rena Jan 05 '23 at 10:20