the values field is required

huangapple go评论73阅读模式
英文:

the values field is required

问题

细节: 我正试图在 asp.net 控制器中设置一个简单的 GET/POST 方法,并使用 Postman 来验证是否设置正确。我在 Stack Overflow 上寻找了类似的问题,但它们没有解决我的问题。

错误: 我的 GET 方法正常工作,但我的 POST 方法出现以下错误。请参见下面的 Postman 截图:

调试: 如果我在 POST 方法内添加一个断点,它永远不会达到该断点。

the values field is required

asp.net 代码:

[ApiController]
[Route("[controller]")]
public class CoursesTakenController : Controller
{
    [HttpGet]
    public IEnumerable<string> Get()
    {
       return new string[] { "value", "value" };
    }

    [HttpPost]
    public Task<ActionResult<string>> Post([FromBody] string values)
    {
        return Ok(values);
    }
}

我也尝试过这样: 但不起作用。

[HttpPost]
public async Task<IActionResult> Post([FromBody] string values)
{
    return Ok();
}
英文:

Detail: I am trying to set up a simple get/post method inside asp.net controller and using postman to set if its set up correctly. I have looked for similar question on stackoverflow and they did not fixed my issue

Error: My Get method works fine but my post method giving an following error. Please see below postman:

debug: if I add a break line inside post method. it is never reaching to that break line

the values field is required

Code in asp.net

[ApiController]
[Route(&quot;[controller]&quot;)]
public class CoursesTakenController : Controller
{
    [HttpGet]
    public IEnumerable&lt;string&gt; Get()
    {
       return new string[] {&quot;value&quot;, &quot;value&quot; }
    }

    [HttpPost]
    public Task&lt;ActionResult&lt;string&gt;&gt; Post([FromBody] string values)
    {
        return Ok(values);
    }
}

I also tried this: but doesnt work

    [HttpPost]
    public async Task&lt;IActionResult&gt; Post([FromBody] string values)
    {
        return Ok();
    }

答案1

得分: 2

您正在发布一个JSON对象,而该方法期望一个字符串。ASP.NET Core使用的默认JSON序列化器System.Text.JsonJsonTokenType处理相当严格,因此要么发布一个字符串,例如只是"RandomText"(或编码为字符串JSON对象 - {"values":"asdasdasd"}),要么更改操作以接受一个对象:

public class Tmp
{
    public string Values { get; set; }
}

[HttpPost]
public async Task<ActionResult<string>> Post([FromBody] Tmp values)
{
   // ...
}
英文:

You are posting a json object while the method expects a string. System.Text.Json (default json serializer used by ASP.NET Core) is pretty restrictive in JsonTokenType handling, so either post a string i.e. just &quot;RandomText&quot; (or encoded into string json object - {\&quot;values\&quot;:\&quot;asdasdasd\&quot;}) or change action to accept an object:

public class Tmp
{
    public required string Values { get; set; }
}

[HttpPost]
public async Task&lt;ActionResult&lt;string&gt;&gt; Post([FromBody] Tmp values)
{
   ...
}

huangapple
  • 本文由 发表于 2023年2月7日 02:23:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75365195.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定