简体   繁体   English

Web API [FromBody] 始终 null

[英]Web API [FromBody] always null

Im currently creating a Web API that writes into a table.我目前正在创建一个写入表的 Web API。 Im using [FromBody] tag to pass the values for the table.我正在使用 [FromBody] 标签来传递表的值。

The problem is that the [FromBody] value is always null. Im using Advanced Rest Client to test my API.问题是 [FromBody] 值始终为 null。我使用高级 Rest 客户端来测试我的 API。

public HttpResponseMessage Post(int id, [FromBody]string value)
{
     //DO Something
}

在此处输入图像描述

The problem is in the type conversion.问题出在类型转换上。 You are sending an array with one value containg a dictionary and trying to recieve a string in the method.您正在发送一个包含一个字典的值的数组,并试图在该方法中接收一个字符串。 ASP.NET can't cast your structure to string and use null as default value. ASP.NET 无法将您的结构转换为string并使用 null 作为默认值。

So, the simple way to test method is to pass a simple string in body.因此,测试方法的简单方法是在正文中传递一个简单的字符串。 But the right way is to change the type of object passing into action method:但正确的方法是改变 object 的类型传递给 action 方法:

public HttpResponseMessage Post(int id, [FromBody]List<Dictionary<string,string>> value)
{
     //DO Something
}

It's strange to parse JSON manually when the system does it, but then you should pass string to the method.当系统解析 JSON 时手动解析很奇怪,但是你应该将string传递给该方法。 Just wrap your body to "" and you'll get a plain JSON in the method.只需将您的身体包裹到"" ,您将在该方法中得到一个普通的 JSON。 Also you can read body manually via StreamReader :您也可以通过StreamReader手动读取正文:

public HttpResponseMessage Post(int id)
{
    using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
    {  
        var plainBody = reader.ReadToEnd();
    }
}

If you don't want the body deserialized, you can just read the string from the Request.Body property.如果您不想反序列化正文,您可以只从Request.Body属性中读取字符串。

public Task<HttpResponseMessage> Post(int id)
{
    var reader = new StreamReader(Request.Body);
    var bodyString = await reader.ReadToEndAsync();

    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM