繁体   English   中英

接受带有 Web 服务 (asmx) 的 json 请求

[英]Accepting a json request with a Webservice (asmx)

我想接受来自 3rd 方工具的帖子,该工具发布了一个复杂的 json 对象。 对于这个问题,我们可以假设一个对象是这样的:

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

我的 .net 代码看起来像

asmx:

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

类.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]
   }
}

我可以接受这个或任何带有 Handler (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)]

我怀疑 UriTemplate 或一些缺失的 BodyTemplate 会起作用。

您需要删除 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;                
}

希望这可以帮助。

暂无
暂无

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

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