c# - ASP.NET web api 无法获取 application/x-www-form-u

我是 web-api 的新手。我想使用 web-api 接收 HTTP POST 数据。 content-type为application/x-www-form-urlencoded,请求体如:

data={"mac":"0004ED123456","model":"SG6200NXL"}(JSON 格式)。

我的 Controller 是这样的:

public void Post([FromBody]string formData)
{
    data.Add(formData);
}

但 formData 始终为空。仅当我将请求正文更改为:

={"mac":"0004ED123456","model":"SG6200NXL"}

我可以找到 {"mac":"0004ED123456","model":"SG6200NXL"} 已保存在我的 formData 字符串中。

所以我的问题是我应该如何接收格式的数据:

data={"mac":"0004ED123456","model":"SG6200NXL"}?

有没有一种简单的方法可以将 JSON 淡化为 C#?

感谢您的帮助!

更新: 我尝试使用模型,但它仍然不适合我。 我的模型是:

public class Device
    {
        public string mac { get; set; }
        public string model { get; set; }
    }

我的 HTTP POST 请求是:

标题:

User-Agent: Fiddler
Content-type: application/x-www-form-urlencoded
Host: localhost:52154
Content-Length: 46

正文:

data={"mac":"0004ED123456","model":"SG6200NX"}

据我所知,我必须使用 Content-type: application/x-www-form-urlencoded 因为 HTTP POST 是由路由器发送的。我的工作是接收数据。

最佳答案

引自 here :

By default, Web API tries to get simple types from the request URI. The FromBody attribute tells Web API to read the value from the request body.

Web API reads the response body at most once, so only one parameter of an action can come from the request body. If you need to get multiple values from the request body, define a complex type.

Second, the client needs to send the value with the following format:

=value

Specifically, the name portion of the name/value pair must be empty for a simple type.

所以,如果你想以 data=string 格式发布数据,你必须创建复杂类型。

public class MyFormData
{
    public string Data { get; set; }
}

然后像这样更新你的 Controller :

public void Post(MyFormData formData)
{
    //your JSON string will be in formData.Data
}

当然,您的其他选择是将内容类型更改为 JSON,但这取决于您的要求。

关于c# - ASP.NET web api 无法获取 application/x-www-form-urlencoded HTTP POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20369361/

相关文章:

json - 处理 HTTP 请求正文中的可选 JSON 字段

javascript - DRYing JSON 有什么众所周知的方法吗

java - 对 kotlin 数据类使用 Jackson @JsonProperty 注释

ruby-on-rails - rails : Restrict API requests to J

javascript - 通过 JSON 发送 64 位值的公认方式是什么?

java - 将 Gson 与接口(interface)类型一起使用

java - 如何使用 Jackson 定义可选的 json 字段

json - Swift 4 JSON Decodable 解码类型更改的最简单方法

javascript - 通过 Angular 资源服务读取 JSON

json - 在 Ubuntu 上将 jq 升级到 1.5