簡體   English   中英

如何修改HttpWebRequest對象的請求主體?

[英]How can I modify the request body of an HttpWebRequest object?

我有一個HttpWebRequest對象,該對象是通過重寫某些第三方庫上的方法而獲得的。 其中的正文包含一些我想刪除並替換的數據。 有沒有一種方法可以讀取HttpWebRequest對象的內容,進行一些替換,然后將其寫回? 我覆蓋的方法允許您在嘗試使用請求對象進行響應之前修改請求對象。

我知道我可以將字節寫到HttpWebRequest ,但是我對如何讀取字節感到困惑。 我想做這樣的事情,但是我做不到。

protected override WebRequest GetWebRequest(Uri uri)
{
    request = (HttpWebRequest)base.GetWebRequest(uri);
    using (var reader = new StreamReader(request.GetRequestStream()))
    {
        var result = reader.ReadToEnd();
        // modify result text and write back
    }

    request.Headers.Add("Authorization", "Bearer " + token);
    return request;
}

恐怕這種方法行不通,原因是,

如果您查看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之類的東西來實現所需的功能。

簡單的答案:您不能。
詳細答案:

HttpWebRequest.GetRequestStream最終打開與遠程主機的套接字連接。 您寫入請求流的所有內容都將發送到主機。

換句話說,請求正文不是存儲在本地。
如果某個第三方庫創建了請求並填充了它的主體,則該主體已發送給主機。

您所能做的就是與庫所有者聯系以更新庫API。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM