JsonResult not serialized with SpanJson
I'm returning a JSON object in a controller action which I would like to use alternative property names for.
Unfortunately it doesn't seem like the [DataMember(Name="differentName")] is working. I'm getting the original property names instead. Am I missing something?
It works well when sending data with help of the FromBody attribute but not when outputting data it seems.
I kinda figured it out. When I use return Json(object) in the controller action, it ignores the attributes. But when using return Ok(object) or return new ObjectResult(object) it works. The problem with this is that the server has to perform content negotiation in the latter case. Does Json(object) use System.Text.Json for some reason?
Yes, JsonResult is not using the TextOutputFormatter, see https://github.com/aspnet/AspNetCore/blob/release/3.1/src/Mvc/Mvc.Core/src/Formatters/SystemTextJsonOutputFormatter.cs concept, but they use internally their own IActionExecuter implementation which then proceeds not to call the TextOutputFormatter but instead has it's own implementation again. https://github.com/aspnet/AspNetCore/blob/master/src/Mvc/Mvc.Core/src/Infrastructure/SystemTextJsonResultExecutor.cs
SpanJson does not provide an implementation for that type, if you want to use SpanJson, you should skip JsonResult.
I'll leave this open and change the title to missing Jsonresult support and flag it as enhancement.
Thanks! I came to the very same conclusion just as I saw your reply :)
When using Newtonsoft, they simply override the default IActionResultExecutor<JsonResult> with their own implementation. Perhaps something similar can be done with SpanJson?
https://github.com/aspnet/AspNetCore/blob/5e953124e6071e10fd71834afc1e45d6e9a04b97/src/Mvc/Mvc.NewtonsoftJson/src/DependencyInjection/NewtonsoftJsonMvcCoreBuilderExtensions.cs#L84
https://github.com/aspnet/AspNetCore/blob/d5fd9fc2faeb079e05e3db31e29dcdea31841eec/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonResultExecutor.cs
Yes, that's the idea. Unfortunately atleast ResponseContentTypeHelper, which is used in those executers is internal. Also JsonResult supports setting options at runtime and that probably won't be supported.