c# - 如何在 Web Api 的主体中传递派生的 JObject 类

标签 c# .net asp.net-mvc webapi

如果我有课

public class TestMe : JObject
{

}
如何在 API 方法中使用它?
public async Task<IHttpActionResult> UpdateMe(int accountId, [FromBody] TestMe sometest)
{
  Console.WriteLine(sometest);
  ...

当我尝试为 body 发布任何内容时,例如:
{
  "Bye": "string"
}
我在 Console.WriteLine 之前收到以下错误行在 UpdateMe方法甚至被击中:
"The parameters dictionary contains an invalid entry for parameter 'sometest' for method 'System.Threading.Tasks.Task`1[System.Web.Http.IHttpActionResult] UpdateMe(Int32, TestMe)' in '<somepath>.Controllers.MiscController'. The dictionary contains a value of type 'Newtonsoft.Json.Linq.JObject', but the parameter requires a value of type 'TestMe'."

最佳答案

Controller 不能接受直接从 JObject 继承的类类(class)。 ( more info here )。我假设在您的情况下,您不知道您将在输入 JSON 中收到哪些属性。这些是可能的解决方案:
只接受 JObject Controller 中的类。

[Route("{accountID}")]
[HttpPost]
public async Task<IHttpActionResult> UpdateMe(int accountId, [FromBody] JObject sometest)
{
    string test = sometest.ToString();

    return Ok(test);
}
您可以使用 JObject随心所欲地上课。示例 - read more here .
这是该问题的一种解决方案。

另一种解决方案是将 JSON 正文作为原始 JSON 读取,并根据您的需要执行此操作:
[Route("{accountID}")]
[HttpPost]
public async Task<IHttpActionResult> UpdateMe(int accountId)
{
    string rawContent = string.Empty;
    using (var contentStream = await this.Request.Content.ReadAsStreamAsync())
    {
        contentStream.Seek(0, SeekOrigin.Begin);
        using (var sr = new StreamReader(contentStream))
        {
            rawContent = sr.ReadToEnd();
            // use raw content here
        }
    }

    return Ok(rawContent);
}

未知输入 JSON 的另一个解决方案是接受 dynamic输入 Controller ,但就个人而言,我不建议这样做。如何实现 read here .为什么我不喜欢它,check this here.

关于c# - 如何在 Web Api 的主体中传递派生的 JObject 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65957725/

相关文章:

c# - Web API - 拦截器 - 拦截异步 Controller 操作

c# - Sitecore:为什么我的管道查询只为我的 droptree 返回一组结果?

c# - 如何在 .net core ef 上应用上述关系的 thenInclude 条件?

c# - 对象的 ActualHeight 和 ActualWidth 始终为零

.Net 运行时负载引用

asp.net-mvc - Azure Active Directory 组织身份验证 Mechasnim

javascript - C# MVC AJAX 请求

javascript - jquery ajax url不包括服务器路径

.net - 为什么在.NET中使用“.pfx”文件

c# - 如何在不修改网页浏览器控件中的文档的情况下注入(inject)并执行javascript函数?