简体   繁体   English

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

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

I've created a web api, which contains method: 我创建了一个Web API,其中包含方法:

POST Settings/SetPropertyValue?propertyName={propertyName}

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

When I visit help page, it shows following 当我访问帮助页面时,它显示以下内容 在此处输入图片说明

When I try to invoke the method from fiddler, using XML example, it works fine, object propertyValue equals to POST value. 当我尝试使用XML示例从fiddler调用该方法时,它工作正常,对象propertyValue等于POST值。

XML POST example: 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>

But how to POST JSON in this case? 但是在这种情况下如何发布JSON? Does JSON handles "simple" data types, like object or string? JSON是否处理“简单”数据类型,例如对象或字符串?

As far as I see there is no body you send. 据我所知,您没有发送任何邮件。 So both the XML and JSON bodies are empty. 因此,XML和JSON主体均为空。

You place all your properties in the query string. 您将所有属性都放在查询字符串中。

I was reading this article about it and it seems you have to start your method with Post to make it a HTTP POST instead of GET. 我正在阅读有关此的文章 ,看来您必须使用Post启动方法以使其成为HTTP POST而不是GET。

Quote: 引用:

Note two things about this method: 请注意有关此方法的两件事:

The method name starts with "Post...". 方法名称以“ Post ...”开头。 To create a new product, the client sends an HTTP POST request. 要创建新产品,客户端发送HTTP POST请求。

This is my test code. 这是我的测试代码。 Maybe it is useful to you: 也许对您有用:

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();

The controller action involved here: 此处涉及的控制器动作:

// 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