我想接受来自发布复杂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]
}
}
我可以接受这个或任何带有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会起作用。
答案 0 :(得分:0)
您迁移的人需要删除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;
}
希望这会有所帮助。