Reputation: 3519
Recently I have decided to go from ASP.NET Core 2.2 to ASP.NET Core 3.1 and did not anticipate all the breaking changes; nearly every part of my application broke as most parts rely on JSON.
To safeguard against future JSON related problems, would it be possible to create an interface, mimicking the current Json implementation and override the default behaviour.
Most of my code relies on these two methods:
Json.Serialize() // used in my razor
Json() // returns an IActionResult
Use case: a Razor Page : Json.Serialize Doc
<script>
var myModel = @Html.Raw(Json.Serialize(Model))
</script>
Use case: a Controller
public async Task<IActionResult> AjaxGetRoleDetails(int id)
{
return Json(await GetUserRoles(id));
}
Here are the methods that I would like, when the above methods are called respectively.
JsonConvert.SerializeObject() // override Json.Serialize
Content(JsonConvert.SerializeObject(), new MediaTypeHeaderValue("application/json")) // override Json()
How can override the system implementation, and call my own implementation for now, and later easily revert to the system's implementation when ASP.NET settles on a JSON implementation.
Upvotes: 1
Views: 1074
Reputation: 1001
The default JSON serializer for ASP.NET Core is now System.Text.Json
So you could migrate over to using it.
Or, if you want to continue using Newtonsoft.Json in ASP.NET Core 3.0 and above, you can update your Startup.ConfigureServices to call AddNewtonsoftJson.
If you require things just like before, for example, in ASP.NET Core 2.2 then you can use the default contract resolver. E.g.
services.AddControllers().AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
Upvotes: 2