使用Web服务(ASMX)接受JSON请求



我想接受第三方工具中发布复杂JSON对象的帖子。对于这个问题,我们可以假设这样的对象:

{
   a: "a value",
   b: "b value",
   c: "c value",
   d: {
     a: [1,2,3]
  }
}

我的.NET代码看起来像

ASMX:

[WebMethod]
public bool AcceptPush(ABCObject ObjectName) { ... }

class.cs

public class ABCObject 
{
  public string a;
  public string b;
  public string c;       
  ABCSubObject d;
}
public class ABCSubObject 
{
  public int[] a;
}

如果我通过对象包装并命名为" objectName":

时,所有这些都可以完美地工作。
{
  ObjectName:
  {
     a: "a value",
     b: "b value",
     c: "c value",
     d: {
       a: [1,2,3]
     }
  }
}

但没有包裹在命名对象中的对象失败。这是发布的。

{
   a: "a value",
   b: "b value",
   c: "c value",
   d: {
     a: [1,2,3]
   }
}

我可以接受处理程序(ASHX(的任何帖子,但是使用vanilla .NET WebService(ASMX(?

我还尝试了:

的组合
    [WebMethod(EnableSession = false)]
    [WebInvoke(
        Method = "POST",
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json, 
        BodyStyle = WebMessageBodyStyle.Bare, 
        UriTemplate="{ObjectName}")]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]

我怀疑乌里蒂姆板或一些缺少的车身板是否有效。

您需要删除WebMethod的参数,然后将JSON字符串映射到Abcobject。

[WebMethod]
public bool AcceptPush() 
{
    ABCObject ObjectName = null;
    string contentType = HttpContext.Current.Request.ContentType;
    if (false == contentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase)) return false;
    using (System.IO.Stream stream = HttpContext.Current.Request.InputStream)
    using (System.IO.StreamReader reader = new System.IO.StreamReader(stream))
    {
        stream.Seek(0, System.IO.SeekOrigin.Begin);
        string bodyText = reader.ReadToEnd(); bodyText = bodyText == "" ? "{}" : bodyText;
        var json = Newtonsoft.Json.Linq.JObject.Parse(bodyText);
        ObjectName = Newtonsoft.Json.JsonConvert.DeserializeObject<ABCObject>(json.ToString());
    }
    return true;                
}

希望这会有所帮助。

最新更新