asp.net OWIN 保存 JSON post 数据
asp.net OWIN save the JSON post data
我使用自托管 OWIN 设置了一个测试命令行应用程序。
我有一个测试控制器,它按预期工作,在获取请求时提供一个静态主页和两个 JSON 格式的值。
我正在使用 JsonFormatter 来格式化所有结果。
我想从 post 请求中读取 JSON 数据。
我可以发送已接受的消息响应,但读取时数据始终为空。
// POST api/values
[HttpPost]
public HttpResponseMessage Post([FromBody]string myString)
{
Console.WriteLine("Terry Tibbs");
Console.WriteLine(myString);
return new HttpResponseMessage(System.Net.HttpStatusCode.Accepted);
}
我在 Chrome 中使用 Postman 到 post 数据如下,但 myString 始终为空。
POST /api/values HTTP/1.1
Host: localhost:8080
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: a966fa36-010d-3e2b-ad66-2f82dcb155ed
{
"myString": "This is new"
}
阅读Parameter Binding in ASP.NET Web API
Using [FromBody]
To force Web API to read a simple type from the request body, add the
[FromBody] attribute to the parameter:
public HttpResponseMessage Post([FromBody] string myString) { ... }
In this example, Web API will use a media-type formatter to read the
value of myString
from the request body. Here is an example client
request.
POST api/values HTTP/1.1
User-Agent: Fiddler
Host: localhost:8080
Content-Type: application/json
Content-Length: 13
"This is new"
When a parameter has [FromBody], Web API uses the Content-Type header
to select a formatter. In this example, the content type is
"application/json" and the request body is a raw JSON string (not a
JSON object).
我使用自托管 OWIN 设置了一个测试命令行应用程序。 我有一个测试控制器,它按预期工作,在获取请求时提供一个静态主页和两个 JSON 格式的值。
我正在使用 JsonFormatter 来格式化所有结果。
我想从 post 请求中读取 JSON 数据。 我可以发送已接受的消息响应,但读取时数据始终为空。
// POST api/values
[HttpPost]
public HttpResponseMessage Post([FromBody]string myString)
{
Console.WriteLine("Terry Tibbs");
Console.WriteLine(myString);
return new HttpResponseMessage(System.Net.HttpStatusCode.Accepted);
}
我在 Chrome 中使用 Postman 到 post 数据如下,但 myString 始终为空。
POST /api/values HTTP/1.1
Host: localhost:8080
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: a966fa36-010d-3e2b-ad66-2f82dcb155ed
{
"myString": "This is new"
}
阅读Parameter Binding in ASP.NET Web API
Using [FromBody]
To force Web API to read a simple type from the request body, add the [FromBody] attribute to the parameter:
public HttpResponseMessage Post([FromBody] string myString) { ... }
In this example, Web API will use a media-type formatter to read the value of
myString
from the request body. Here is an example client request.POST api/values HTTP/1.1 User-Agent: Fiddler Host: localhost:8080 Content-Type: application/json Content-Length: 13 "This is new"
When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object).