【问题标题】:Simple types JSON serialization in ASP.net Web-apiASP.net Web-api 中的简单类型 JSON 序列化
【发布时间】:2014-01-20 11:27:21
【问题描述】:

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

POST Settings/SetPropertyValue?propertyName={propertyName}

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

当我访问帮助页面时,它显示以下

当我尝试从提琴手调用该方法时,使用 XML 示例,它工作正常,对象 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 是否处理“简单”数据类型,如对象或字符串?

【问题讨论】:

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


    【解决方案1】:

    据我所知,您没有发送任何尸体。所以 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
    }
    

    【讨论】:

    • 请解释一下你的答案,因为我完全不明白,你的意思是什么..
    • 对不起,您好像不明白,我到底在问什么。我可以将对象作为 XML 发布,但是如何将对象作为 JSON 发布?我上面的代码已经在工作并接受帖子,但似乎我无法将简单数据类型发布为 JSON。为了将方法标记为帖子,我在其上方使用了 [HttpPost]。
    • 您是否发送了请求中的内容类型? Content-Type: application/json
    • 我当然愿意!请告诉我,如何将简单数据类型作为 JSON 发布?不是 DataContract 类,序列化为 JSON 对象,而只是 String 例如。
    • 如我所见,Web-Api 在序列化 JSON 时会这样做:如果有一个类,例如 class Person { string Name; },并且我们正在获取或发布该类的对象,那么 JSON 对象将看起来像 @ 987654327@,但如果我们返回简单类型,如字符串“John Doe”,我们将得到 John Doe 作为响应,它未被识别为有效 JSON,但我能够从我的C#、Fiddler 和 Java 客户端,所以问题基本上解决了。感谢您的努力!
    猜你喜欢
    • 2012-09-20
    • 1970-01-01
    • 2021-09-01
    • 1970-01-01
    • 2013-09-25
    • 1970-01-01
    • 2014-04-27
    • 1970-01-01
    相关资源
    最近更新 更多