问题
I have asp.net core 2.2 web Application. The application contains Command and Query Actions, Command Actions must return typed json response:
{
$type:"A.B.Customer, x.dll ",
id: 11231,
name: "Erwin .."
}
Query Actions must return non typed response:
{
id: 34234,
name: "Erwin .. "
}
We can choose one outputformatter for Json responses at startup.
services.AddMvc().AddJsonOptions(o =>
{
SerializerSettings.TypeNameHandling=Newtonsoft.Json.TypeNameHandling.Objects
// SerializerSettings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.None
}
So How can I change output formatter for same response type (application/json) by action?
回答1:
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);
来源:https://stackoverflow.com/questions/57071449/how-can-i-change-serialization-approach-typed-none-for-some-actions-in-asp-net