c# - ASP.NET WebAPI 的哪一部分负责将动态解析为 JObject

标签 c# asp.net asp.net-web-api json.net

我有一个具有以下方法的 ApiController:

public void Post(dynamic data)
{
    Type actualType = data.GetType(); // returns JObject
}

当我进行 AJAX 调用时,将 JSON 数据发送到 Controller ,“数据”参数的实际类型是 JObject(来自 Newtonsoft.Json 库)。 WebAPI 的哪一部分负责将此请求中的数据绑定(bind)到 JObject?它是模型 Binder 吗?如果有,是哪一个? (有几个内置的,例如'MutableObjectModelBinder','TypeMatchModelBinder'等)

最佳答案

它是 JsonMediaTypeFormatter。 ASP.NET Web API 默认的 JSON Formatter 是 JSON.NET。这就是你的动态对象被转换为 JObject 的原因。不过,您可以将默认格式化程序切换为 DataContractJsonSerializer。

查看 this article .

JSON Media-Type Formatter

JSON formatting is provided by the JsonMediaTypeFormatter class. By default, JsonMediaTypeFormatter uses the Json.NET library to perform serialization. Json.NET is a third-party open source project.

If you prefer, you can configure the JsonMediaTypeFormatter class to use the DataContractJsonSerializer instead of Json.NET. To do so, set the UseDataContractJsonSerializer property to true:

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter; json.UseDataContractJsonSerializer = true;

您可以从 WebApiConfig 更改您的 JSON 格式化程序配置

关于c# - ASP.NET WebAPI 的哪一部分负责将动态解析为 JObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28046037/

相关文章:

c# - 带图像的 WPF 按钮不出现

C#:通过变量引用类

asp.net - 为什么我在尝试使用 URL 访问下载 SSRS 报告时收到 500 错误?

asp.net - 发送HTTP header 后服务器无法设置状态-Web API CORS

c# - 任务和异常静默

c# - MVC Identity 2.0 和管理角色

asp.net - 处理 ASP.Net MVC 中的过期 header

c# - 使用 ormlite (SQL Server) 和 C# 中的存储过程删除和更新

c# - 如何使用 Asp.NET Web Api 检测高 CPU 和长响应时间问题

c# - 将 C# 对象发送到 webapi Controller