英文:
the values field is required
问题
细节: 我正试图在 asp.net 控制器中设置一个简单的 GET/POST 方法,并使用 Postman 来验证是否设置正确。我在 Stack Overflow 上寻找了类似的问题,但它们没有解决我的问题。
错误: 我的 GET 方法正常工作,但我的 POST 方法出现以下错误。请参见下面的 Postman 截图:
调试: 如果我在 POST 方法内添加一个断点,它永远不会达到该断点。
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
Code in 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);
}
}
I also tried this: but doesnt work
[HttpPost]
public async Task<IActionResult> Post([FromBody] string values)
{
return Ok();
}
答案1
得分: 2
您正在发布一个JSON对象,而该方法期望一个字符串。ASP.NET Core使用的默认JSON序列化器System.Text.Json
对JsonTokenType
处理相当严格,因此要么发布一个字符串,例如只是"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 "RandomText"
(or encoded into string json object - {\"values\":\"asdasdasd\"}
) or change action to accept an object:
public class Tmp
{
public required string Values { get; set; }
}
[HttpPost]
public async Task<ActionResult<string>> Post([FromBody] Tmp values)
{
...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论