如果我有课
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/