本文介绍了FromBody 字符串参数为 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是非常基本的事情,但我很难弄清楚我哪里出错了.

This is probably something very basic, but I am having trouble figuring out where I am going wrong.

我试图从 POST 正文中获取一个字符串,但jsonString"仅显示为 null.我也想避免使用模型,但这也许是不可能的.我用 PostMan 打的代码是这个块:

I am trying to grab a string from the body of a POST, but "jsonString" only shows as null. I also want to avoid using a model, but maybe this isn't possible. The piece of code that I am hitting with PostMan is this chunk:

[Route("Edit/Test")]
[HttpPost]
public void Test(int id, [FromBody] string jsonString)
{
    ...
}

也许这是我对邮递员做的不正确的事情,但我一直在尝试在正文的值部分使用=test"(如有关该主题的其他问题中所见) - x-www-form-urlencoded 部分,密钥为 jsonString,什么都没有.我也尝试过使用 raw - text 和 raw - text/plain.我得到了 id,所以我知道 url 是正确的.对此的任何帮助将不胜感激.

Maybe it is something I am doing incorrectly with postman, but I have been trying to use "=test" (as seen in other questions asked about this topic) in the value section of the body - x-www-form-urlencoded section with the key as jsonString and nothing. I have also tried using raw - text and raw - text/plain. I get the id so I know the url is correct. Any help with this would be greatly appreciated.

PostMan 目前是这样设置的:

PostMan is set up like this currently:

POST http://localhost:8000/Edit/Test?id=111
key = id  value = 111
Body - x-www-form-urlencoded
key = jsonString  value = "=test"

推荐答案

通过使用 [FromBody] 声明 jsonString 参数,您告诉 ASP.NET Core 使用输入格式化程序来绑定提供的 JSON (或 XML)到模型.所以你的测试应该可以工作,如果你提供一个简单的模型类

By declaring the jsonString parameter with [FromBody] you tell ASP.NET Core to use the input formatter to bind the provided JSON (or XML) to a model. So your test should work, if you provide a simple model class

public class MyModel
{
    public string Key {get; set;}
}

[Route("Edit/Test")]
[HttpPost]
public void Test(int id, [FromBody] MyModel model)
{
    ... model.Key....
}

和发送的 JSON 之类的

and a sent JSON like

{
    key: "value"
}

当然,您可以跳过模型绑定,直接通过访问控制器中的 HttpContext.Request 来检索提供的数据.HttpContext.Request.Body 属性为您提供内容流,或者您可以通过 HttpContext.Request.Forms 访问表单数据.

Of course you can skip the model binding and retrieve the provided data directly by accessing HttpContext.Request in the controller. The HttpContext.Request.Body property gives you the content stream or you can access the form data via HttpContext.Request.Forms.

我个人更喜欢模型绑定,因为类型安全.

I personally prefer the model binding because of the type safety.

这篇关于FromBody 字符串参数为 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 22:21