我在使用Xamarin构建的iOS应用程序中无法进行Web服务调用。这个完全相同的代码,它生成一个请求并使用HTTPWebRequest GetResponse()来获取响应,该代码曾经工作过,但现在在尝试获取响应时崩溃了。它在ReadToEnd上崩溃,表示参数不能为null。此代码自工作以来一直保持不变。我知道400会有响应,因为PostMan可以工作,当我从Xamarin应用程序拨打电话时,我还可以看到后端的日志。搜索stackoverflow揭示了某些人已通过升级Xamarin解决了此问题,并且它与它使用的mono运行时有关。但是最新版本的Xamarin对我来说是一样的事情。
...
} catch(WebException ex) {
try {
if(ex.Response == null || ex.Status != WebExceptionStatus.ProtocolError) throw;
...
Stream data = ex.Response.GetResponseStream(); if(data==null) return "ERR";
StreamReader reader = new StreamReader(data); if(reader==null) return "ERR";
string responseFromServer = reader.ReadToEnd();
预期结果应该是我的GetResponse在HTTP 400的情况下确实会生成WebException,但是仍然应该有一个响应正文可供读取。
这是该异常的堆栈跟踪:
2019-04-02 09:15:17.367099-0400 ******.iOS[41201:4512789] *****> System.Net.WebException: Value cannot be null.
Parameter name: src ---> System.ArgumentNullException: Value cannot be null.
Parameter name: src
at System.Buffer.BlockCopy (System.Array src, System.Int32 srcOffset, System.Array dst, System.Int32 dstOffset, System.Int32 count) [0x00003] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.2.1.16/src/Xamarin.iOS/mcs/class/corlib/ReferenceSources/Buffer.cs:39
at System.Net.WebResponseStream+<ProcessRead>d__49.MoveNext () [0x00082] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.2.1.16/src/Xamarin.iOS/mcs/class/System/System.Net/WebResponseStream.cs:203
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest+<RunWithTimeoutWorker>d__241`1[T].MoveNext () [0x000e8] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.2.1.16/src/Xamarin.iOS/mcs/class/System/System.Net/HttpWebRequest.cs:956
--- End of stack trace from previous location where exception was thrown ---
at System.Net.WebConnectionStream.Read (System.Byte[] buffer, System.Int32 offset, System.Int32 count) [0x00070] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.2.1.16/src/Xamarin.iOS/mcs/class/System/System.Net/WebConnectionStream.cs:136
at System.IO.Stream.ReadByte () [0x00007] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.2.1.16/src/Xamarin.iOS/mcs/class/referencesource/mscorlib/system/io/stream.cs:758
at *****.API.callService (System.String endpt, System.String parm, System.Boolean isGet) [0x003e9] in /Users/****/Projects/*****/*****/API.cs:80