2017-09-01 72 views
3

我在我的代碼庫,其生成並返回一個現成的發送HTTP POST消息作爲System.Net.HttpWebRequest對象(傳統)方法:從HttpWebRequest對象獲取正文文本?

public HttpWebRequest GetHttpWebRequest(string body, string url, string contentType) 
{ 
    HttpWebRequest request = HttpWebRequest.CreateHttp(url); 
    request.Method = "POST"; 
    // (More setup stuff here...) 

    using (var writer = new StreamWriter(request.GetRequestStream())) 
    { 
     writer.Write(body); 
    } 

    return request; 
} 

我想寫一個單元測試這證實了HttpWebRequest由此方法返回的實例實際上具有傳遞給參數body中的方法的消息正文文本。

問題:如何獲取HttpWebRequest對象的正文(沒有實際發送HTTP請求)?

的東西,我試過到目前爲止:

  • new StreamReader(myHttpWebRequest.GetRequestStream()).ReadToEnd() - 在運行時無法與ArgumentException: Stream was not readable.
  • HttpWebRequest類似乎並不具備,將允許獲得的任何財產/讀取HTTP消息正文如Body,Message,Text等。
+0

你會被測試,如果你會成功嗎? HttpWebRequest?或者它的迴應?我只是問,因爲這裏感覺不太對勁。 – Stefan

+0

@Stefan我的想法是測試我的自定義代碼,它將「body」參數值設置到創建的HttpWebRequest上。 (我可以創建幾個單元測試方法,確保我的代碼能夠正確處理各種角落案例。) –

+0

如何將http偵聽器添加到代碼中併發出真正的http請求。 –

回答

1

我會寫一個http偵聽器併發出真正的http請求。

以下是使用WCF +客戶端代碼的示例服務器。只需撥打await TestClient.Test();(您也可以像http://localhost:8088/TestServer/Dummy瀏覽器測試服務器)

using Newtonsoft.Json; 
using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Net.Http; 
using System.ServiceModel; 
using System.ServiceModel.Channels; 
using System.ServiceModel.Web; 
using System.Text; 
using System.Threading.Tasks; 

namespace SO 
{ 
    [ServiceContract] 
    public class TestServer 
    { 
     static WebServiceHost _host = null; 
     public static Task Start() 
     { 
      var tcs = new TaskCompletionSource<object>(); 

      try 
      { 
       _host = new WebServiceHost(typeof(TestServer), new Uri("http://0.0.0.0:8088/TestServer")); 
       _host.Opened += (s, e) => { tcs.TrySetResult(null); }; 
       _host.Open(); 

      } 
      catch(Exception ex) 
      { 
       tcs.TrySetException(ex); 
      } 

      return tcs.Task; 
     } 

     //A method that accepts anything :) 
     [OperationContract, WebInvoke(Method = "*", UriTemplate ="*")] 
     public Message TestMethod(Stream stream) 
     { 
      var ctx = WebOperationContext.Current; 

      var request = ctx.IncomingRequest.UriTemplateMatch.RequestUri.ToString(); 

      var body = new StreamReader(stream).ReadToEnd(); 

      Console.WriteLine($"{ctx.IncomingRequest.Method} {request}{Environment.NewLine}{ctx.IncomingRequest.Headers.ToString()}BODY:{Environment.NewLine}{body}"); 

      return ctx.CreateTextResponse(JsonConvert.SerializeObject(new { status = "OK", data= "anything" }), "application/json", Encoding.UTF8); 
     } 
    } 

    public class TestClient 
    { 
     public static async Task Test() 
     { 
      await TestServer.Start(); 

      var client = new HttpClient(); 
      var objToSend = new { name = "L", surname = "B" }; 
      var content = new StringContent(JsonConvert.SerializeObject(objToSend)); 
      var response = await client.PostAsync("http://localhost:8088/TestServer/TestMethod?aaa=1&bbb=2", content); 
      Console.WriteLine(response.StatusCode); 
      Console.WriteLine(await response.Content.ReadAsStringAsync()); 

     } 
    } 
}