ASP.net Web-api中的简单类型JSON序列化

时间:2014-01-20 11:27:21

标签: c# json asp.net-web-api

我创建了一个web api,其中包含方法:

POST Settings/SetPropertyValue?propertyName={propertyName}

public object SetPropertyValue(string propertyName, object propertyValue)
        {
            switch (propertyName)
            {
                  //Do the property assignment
            }
        }

当我访问帮助页面时,它会显示以下enter image description here

当我尝试使用XML示例从fiddler调用该方法时,它工作正常,对象propertyValue等于POST值。

XML POST示例:

POST http://localhost:99/webapi/Settings/SetPropertyValue?propertyName=myProperty HTTP/1.1
Content-Type: text/xml; charset=UTF-8
Host: localhost:99
Expect: 100-continue
Connection: Keep-Alive

<anyType>
  true
</anyType>

但是在这种情况下如何POST JSON? JSON是否处理“简单”数据类型,如对象或字符串?

1 个答案:

答案 0 :(得分:0)

据我所知,你发送的身体没有。所以XML和JSON主体都是空的。

将所有属性放在查询字符串中。

我正在阅读有关它的this article,看来您必须使用Post启动方法,使其成为HTTP POST而不是GET。

  

<强>引用:

     

请注意有关此方法的两件事:

     

方法名称以“Post ...”开头。要创建一个新产品,   客户端发送HTTP POST请求。

这是我的测试代码。也许它对你有用:

WebRequest request = HttpWebRequest.Create("http://localhost:12345/api/Values");

byte[] byteArray = Encoding.UTF8.GetBytes("5");

request.ContentLength = byteArray.Length;
request.ContentType = "application/json";

request.Method = "POST";

Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();

WebResponse response = request.GetResponse();

Stream data = response.GetResponseStream();

StreamReader reader = new StreamReader(data);
// Read the content.
string responseFromServer = reader.ReadToEnd();

此处涉及的控制器操作:

// POST api/values
public void Post([FromBody]string value)
{
    // check the value here
}