c# – 给定HttpResponseMessage,如何读取请求的内容?
给定一个System.Net.Http.HttpResponseMessage,我可以获得很多关于我通过response.RequestMessage做出的请求的信息,例如
response.RequestMessage.RequestUri // the url of the request response.RequestMessage.Method // the HTTP method 但是,我无法找到一种方法来获得有用的东西 response.RequestMessage.Content // a StringContent instance 我查看了StringContent的属性树,但我无法弄清楚如何以Watch Window中的方式将其内容作为常规字符串. 有什么建议? 解决方法
使用
ILSpy分析
System.Net.Http.dll v2.2.29.0 表明System.Net.Http.HttpClientHandler.CreateResponseMessage(初始化HttpResponse对象)对相应的HttpRequest的.Content没有任何作用.这意味着如果它首先不是null,那么内容对象本身应该仍然可用.
当对被处理对象执行操作时,抛出 当然,搜索HttpContent.Dispose()用户会给我们带来罪魁祸首 – System.Net.Http.HttpClient.SendAsync(),它在发送数据后调用System.Net.Http.HttpClient.DisposeRequestContent(). 现在,关于做什么. HttpContent.Dispose()所做的就是关闭对象的流并设置一个标志.但是,StreamContent(或者更确切地说是它的父,ByteArrayContent)将数据保存在.content字段中 – 这不会被处置所触及! 唉,两种直接读取它的方法都受到保护,所有使用它们的公共方法都首先检查该标志.因此,阅读它的唯一方法是使用反射(插图是在IronPython中,注释是针对C#等效的): >>> sc=System.Net.Http.StringContent("abcdefghijklmnopqrstuvwxyz") #in C#,the following is `type(StringContent)' (this is what it actually does) >>> scd=System.Reflection.TypeDelegator(System.Net.Http.StringContent) >>> print scd.GetField("content",System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Instance) None #because the field is in ByteArrayContent and is private >>> bacd=System.Reflection.TypeDelegator(System.Net.Http.ByteArrayContent) >>> bacd.GetField("content",System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Instance) <System.Reflection.RtFieldInfo object at 0x000000000000002C [Byte[] content]> # `_' is last result >>> _.GetValue(sc) Array[Byte]((<System.Byte object at 0x000000000000002D [97]>,<System.Byte objec t at 0x000000000000002E [98]>,<System.Byte object at 0x000000000000002F [99]>,<...> 在C#中,这看起来像: type(ByteArrayContent) .GetField("content",BindingFlags.NonPublic|BindingFlags.Instance) .GetValue(content) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |