繁体   English   中英

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

[英]Simple types JSON serialization in ASP.net Web-api

我创建了一个Web API,其中包含方法:

POST Settings/SetPropertyValue?propertyName={propertyName}

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

当我访问帮助页面时,它显示以下内容 在此处输入图片说明

当我尝试使用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>

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

据我所知,您没有发送任何邮件。 因此,XML和JSON主体均为空。

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

我正在阅读有关此的文章 ,看来您必须使用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
}

暂无
暂无

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

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