【问题标题】:asp.net OWIN save the JSON post dataasp.net OWIN 保存 JSON 发布数据
【发布时间】:2016-06-28 13:45:29
【问题描述】:

我使用自托管 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 来发布如下数据,但 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"
}

【问题讨论】:

    标签: asp.net json httprequest owin httpresponse


    【解决方案1】:

    阅读Parameter Binding in ASP.NET Web API

    使用 [FromBody]

    要强制 Web API 从请求正文中读取简单类型,请添加 [FromBody] 属性到参数:

    public HttpResponseMessage Post([FromBody] string myString) { ... }
    

    在本例中,Web API 将使用媒体类型格式化程序来读取 来自请求正文的 myString 的值。这是一个示例客户端 请求。

    POST api/values HTTP/1.1
    User-Agent: Fiddler
    Host: localhost:8080
    Content-Type: application/json
    Content-Length: 13
    
    "This is new"
    

    当参数有 [FromBody] 时,Web API 使用 Content-Type 标头 选择格式化程序。在此示例中,内容类型为 "application/json" 并且请求正文是原始 JSON 字符串 (不是 JSON 对象)

    【讨论】:

    • 非常感谢。如果您不是您要搜索的内容,Google 将无济于事。 :)
    猜你喜欢
    • 1970-01-01
    • 2014-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多