2013-05-07 40 views
2

我已經多次看過這個主題,但沒有任何解決方案對我有所幫助,我不知道爲什麼沒有任何工作。從C中的context.httprequest中讀取原始數據

我有一個C#web部分,我只是試圖讀取http post請求的數據內容。在請求中有一些XML,但是當我嘗試在Web部件中讀取它時,這並沒有顯示出來。它只給我頭數據和一些服務器變量。

我正在嘗試閱讀的請求是通過Chrome的簡單休息擴展提交的。當我用提琴手監控時,我可以看到請求,當我點擊TextView時,我可以看到所有的XML沒有問題。那麼爲什麼它不顯示在服務器上呢?

我試過使用Context.Request.SaveAs(),但似乎只給我頭數據。我也嘗試循環遍歷Context.Request.Params並打印每個參數,但沒有一個包含xml。

最後,我試着用閱讀

Context.Request.ContentEncoding      
     .GetString(Context.Request.BinaryRead(Context.Request.TotalBytes)) 

string strmContents = ""; 
using (StreamReader reader = new StreamReader(Context.Request.InputStream)) 
{ 
    while (reader.Peek() >= 0) 
    { 
     strmContents += reader.ReadLine(); 
    } 
} 

但兩者的這些方法導致空字符串請求的內容。

真正讓我困惑的是,如果我看一下Context.Request.ContentLength,它與我XML中的字符數相同!我知道內容正在通過,但我不知道如何訪問它。

回答

9

我覺得不好發表這個,因爲代碼不是我的,但我找不到原來的帖子。

這個擴展方法對我來說非常有用,你只需像這樣使用它: HttpContext.Current.Request.ToRaw();

using System.IO; 
using System.Web; 
using log4net; 

namespace System.Web.ExtensionMethods 
{ 
    /// <summary> 
    /// Extension methods for HTTP Request. 
    /// <remarks> 
    /// See the HTTP 1.1 specification http://www.w3.org/Protocols/rfc2616/rfc2616.html 
    /// for details of implementation decisions. 
    /// </remarks> 
    /// </summary> 
    public static class HttpRequestExtensions 
    { 

    /// <summary> 
    /// Dump the raw http request to a string. 
    /// </summary> 
    /// <param name="request">The <see cref="HttpRequest"/> that should be dumped.    </param> 
    /// <returns>The raw HTTP request.</returns> 
    public static string ToRaw(this HttpRequest request) 
    { 
     StringWriter writer = new StringWriter(); 

     WriteStartLine(request, writer); 
     WriteHeaders(request, writer); 
     WriteBody(request, writer); 

     return writer.ToString(); 
    } 

    public static string GetBody(this HttpRequest request) 
    { 
     StringWriter writer = new StringWriter(); 
     WriteBody(request, writer); 

     return writer.ToString(); 
    } 

    private static void WriteStartLine(HttpRequest request, StringWriter writer) 
    { 
     const string SPACE = " "; 

      writer.Write(request.HttpMethod); 
      writer.Write(SPACE + request.Url); 
      writer.WriteLine(SPACE + request.ServerVariables["SERVER_PROTOCOL"]); 
    } 


    private static void WriteHeaders(HttpRequest request, StringWriter writer) 
    { 
      foreach (string key in request.Headers.AllKeys) 
      { 
        writer.WriteLine(string.Format("{0}: {1}", key, request.Headers[key])); 
      } 

      writer.WriteLine(); 
     } 


     private static void WriteBody(HttpRequest request, StringWriter writer) 
     { 
      StreamReader reader = new StreamReader(request.InputStream); 

      try 
      { 
       string body = reader.ReadToEnd(); 
       writer.WriteLine(body); 
      } 
      finally 
      { 
       reader.BaseStream.Position = 0; 
      } 
     } 
} 
} 
+0

只要您的帖子正在幫助某個地球上的某個人,永遠不會覺得*不好*。 – RBT 2017-11-30 12:21:17

相關問題