简体   繁体   English

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

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

I would like to accept a post from a 3rd party tool which posts a complex json object.我想接受来自 3rd 方工具的帖子,该工具发布了一个复杂的 json 对象。 For this question we can assume an object like this:对于这个问题,我们可以假设一个对象是这样的:

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

my .net code looks like我的 .net 代码看起来像

asmx: asmx:

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

class.cs类.cs

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

This all works perfectly if I pass the object when it is wrapped and named "ObjectName":如果我在包装并命名为“ObjectName”时传递对象,这一切都可以完美运行:

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

But fails without the object wrapped in an named object.但是如果没有包含在命名对象中的对象就会失败。 Which is what is posted.发布的内容是什么。

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

I can accept this or any post with a Handler (ashx), but is this possible using a vanilla .Net Webservice (asmx)?我可以接受这个或任何带有 Handler (ashx) 的帖子,但这是否可以使用 vanilla .Net Webservice (asmx)?

I also tried combinations of:我还尝试了以下组合:

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

I suspect UriTemplate or some missing BodyTemplate would work.我怀疑 UriTemplate 或一些缺失的 BodyTemplate 会起作用。

You mignt need to remove WebMethod's parameter, and map json string to ABCObject manually.您需要删除 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;                
}

Hope this helps.希望这可以帮助。

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

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