There are multiple ways to do that.
One would be to directly call JSON.NET Methods and pass your settings to it.
JsonSerializerSettings settings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects
};
return base.Content(JsonConvert.SerializeObject(query, settings), "application/json");
Alternatively, return a JsonResult
JsonSerializerSettings settings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects
};
return new JsonResult(query, settings);
Be careful with the second example. In .NET Core 3.0, JSON.NET isn't hard-wired into ASP.NET Core anymore and ASP.NET Core ships w/o JSON.NET and uses the new System.Text.Json classes base don span.
In ASP.NET Core 2.x, JsonResult accepts JsonSerializerSettings as second parameter.
From ASP.NET Core 3.x, JsonResult accepts object and depending on the serializer used, a different type is expected.
This means, if you use the second example in your code, it will (at first) break, when migrating to ASP.NET Core 3.0, since it has no dependencies on JSON.NET anymore. You can easily add JSON.NET Back to it by adding the Newtonsoft.Json package to your project and add
servics.AddNewtonsoftJson();
in your ConfigureServices methods, to use JSON.NET again. However, if in future, you ever decide to move away from JSON.NET and use System.Text.Json or any other Json serializer, you have to change all places where that's used.
Feel free to change that to an extension method, create your own action result class inheriting from JsonResult etc.
public class TypelessJsonResult : JsonResult
{
public TypelessJsonResult(object value) : base(value)
{
SerializerSettings.TypeNameHandling = TypeNameHandling.None;
}
}
and reduce your controller's action code to
return new TypelessJsonResult(query);