FromBody收到的帖子导致可序列化错误 [英] Post received by FromBody causes serializable error

查看:162
本文介绍了FromBody收到的帖子导致可序列化错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是基本设置,我有一个asp.net核心webapi控制器(在c#中),其发布功能如下:

Here's the basic setup, I have an asp.net core webapi controller (in c#) with a post function like so:

[HttpPost]
public ActionResult<string> Post([FromBody] string Name)
{
     //Do some processing with the "Name" argument...
     return Ok( "Success!" );
}

我正在尝试将以下原始JSON请求正文发送到此函数:

I'm trying to send the following raw JSON request body to this function:

{
    "Name": "Foo"
}

但是当使用上面的正文向该函数发送发布请求时,我在服务器控制台中返回以下错误:

But when send a post request to this function with the body above, I get back the following error in the server console:

正在执行ObjectResult,写入类型为'Microsoft.AspNetCore.Mvc.SerializableError'的值"

"Executing ObjectResult, writing value of type 'Microsoft.AspNetCore.Mvc.SerializableError'"

这是客户端上的错误

{ ":[ 解析值时遇到意外字符:{.Path,第1行,位置1." ] }

{ "": [ "Unexpected character encountered while parsing value: {. Path '', line 1, position 1." ] }

我尝试在函数的开头设置一个断点,但是它甚至没有触发!为什么会出现可序列化的错误?

I tried setting a break point at the beginning of the function but it doesn't even trigger! Why am I getting a serializable error?

推荐答案

可序列化的错误实际上是JSON.NET的解析错误,但该问题实际上与解析JSON无关.

The serializable error is actually a parsing error from JSON.NET, but the problem actually has nothing to do with parsing JSON.

真正的问题是ASP.NET Core希望将JSON主体解析为对象/DTO.因此,您可以使用两个选项来解决此问题:

The real issue is that ASP.NET Core expects to parse a JSON body into an object/DTO. So you have two options you can use to fix the problem:

  1. 为您的单个参数创建一个简单的DTO容器对象,例如:

  1. Make a simple DTO container object for your single parameter e.g.:

public class SimpleObject { 
    public string Name { get; set; } 
}

  • 不要在请求正文中传递完整的JSON对象,而只需使用简单的字符串即可,例如:"My parameter string"

    这篇关于FromBody收到的帖子导致可序列化错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆