我有一个只捕获入站数据的Web服务。如果传入数据是字符串化的JSON数组,则服务器返回500级错误:
ExceptionType : "System.InvalidOperationException"
Message: "Type 'System.Collections.Generic.IDictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' is not supported for deserialization of an array."
at System.Web.Script.Serialization.ObjectConverter.ConvertListToObject(IList list, Type type, JavaScriptSerializer serializer, Boolean throwOnError, IList& convertedList)
.........
我做了一些测试,它与字符串化JSON数组中的括号有关。发送字符串化的JSON对象(只是花括号)不会导致错误。即"{"id":111,"val":"x"}"
与"[{"id":111,"val":"x"}]"
令我困惑的是,我没有在web方法中进行任何反序列化。 在我可以访问请求之前,这一切都发生在上游。网络方法如下:
[WebMethod]
[ScriptMethod]
public void CatchData()
{
HttpRequest inboundRequest = HttpContext.Current.Request;
System.IO.Stream stream = inboundRequest.InputStream;
stream.Position = 0;
string contents = "";
using (System.IO.StreamReader reader = new System.IO.StreamReader(stream, Encoding.UTF8))
{
contents = reader.ReadToEnd();
}
}
两个问题:
我需要更改哪些内容,以便web方法可以处理字符串化JSON中的括号?
这到底发生了什么?我花了一段时间才意识到HttpContext.Current.Request.InputStream正在被Web方法的上游使用,所以为了重新读取它的内容,我需要将它的位置设置为0.当内容类型时上游发生了什么设置为application / json?如果将内容类型设置为应用程序/文本,则无需重置流。
答案 0 :(得分:0)
您显然在上游配置了正在读取请求的处理程序。我想象无论是webmethod还是scriptmethod都在添加处理程序,不过如果你在一个复杂的项目中,httphandler可能会在游戏中。如果不了解更多关于整个解决方案的信息,就不可能有更好的答案。
如果您只想自己处理任何原始输入,请构建并注册httphandler。