[英]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.