如何修改HttpWebRequest对象的请求主体?

时间:2018-01-18 05:43:26

标签: c#

我有一个string[] includes = { "PlayList", "PlayListSong" }; var playLists =_unitOfWork.PlayListSongRepository.GetWithMultipleInclude( e => e.UserId==userId,includes ).Select(x=>x.PlayList).ToList(); /// <summary> /// Inclue multiple /// </summary> /// <param name="predicate"></param> /// <param name="include"></param> /// <returns></returns> public IEnumerable<TEntity> GetWithMultipleInclude( System.Linq.Expressions.Expression<Func<TEntity, bool>> predicate, string[] include) { IQueryable<TEntity> query = this.DbSet; foreach (string inc in include) { query = query.Include(inc); } return query.Where(predicate).ToList<TEntity>() ; } 对象,我通过覆盖某个第三方库上的方法获得。其中包含一些我想要删除和替换的数据。有没有办法可以读取HttpWebRequest对象的内容,做一些替换,然后再写回来?我覆盖的方法允许您在尝试使用它来获取响应之前修改请求对象。

我知道我可以将字节写入HttpWebRequest,但我仍然坚持如何阅读它。我想做这样的事,但我做不到。

HttpWebRequest

2 个答案:

答案 0 :(得分:0)

我担心这种方法不起作用,理由是,

如果你看一下HttpWebRequest.cs

的第1490行
        /// <devdoc>
        /// <para>Gets a <see cref='System.IO.Stream'/> that the application can use to write request data.
        ///    This property returns a stream that the calling application can write on.
        ///    This property is not settable.  Getting this property may cause the
        ///    request to be sent, if it wasn't already. Getting this property after
        ///    a request has been sent that doesn't have an entity body causes an
        ///    exception to be thrown.
        ///</para>
        /// </devdoc>
        public Stream GetRequestStream(out TransportContext context) {

它说明一旦你收到财产请求就会被发送。这意味着您将无法修改它。作为示例,您可以尝试以下代码

            var postData = "thing1=hello";
            postData += "&thing2=world";
            var data = Encoding.ASCII.GetBytes(postData);

            var request = (HttpWebRequest)WebRequest.Create("https://www.google.com.au/");
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

第二个stram.Write将失败。

你可以使用像Fiddler.Core这样的东西来实现你所需要的。

答案 1 :(得分:0)

简单回答:你不能。
详细答案:

HttpWebRequest.GetRequestStream最终会打开与远程主机的套接字连接。您写入请求流的所有内容都将发送给主机。

换句话说,请求正文不会存储在本地 如果某个第三方图书馆已经创建了请求并填充了其正文,则已将正文发送给主持人。

您所能做的就是联系图书馆所有者以更新图书馆API。