我已经多次看到这个主题,但没有一个解决方案对我有帮助,我不知道为什么没有任何效果。
我有一个 C# web 部件,我只是想读取一个 http post 请求的数据内容。请求中有一些 xml,但是当我尝试在 web 部件中读取它时,这并没有显示出来。它只给我 header 数据和一些服务器变量。
我尝试阅读的请求是通过 Chrome 的 Simple Rest 扩展提交的。当我用 fiddler 监控时,我可以看到请求,当我点击 TextView 时,我可以看到所有的 XML 没有问题。那么为什么它不显示在服务器上?
我尝试使用 Context.Request.SaveAs()
,但这似乎只提供了 header 数据。我还尝试遍历 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 中的字符数相同!我知道内容正在通过,但我不知道如何访问它。
最佳答案
我觉得不好意思发帖,因为代码不是我的,但我找不到原始帖子。
这个扩展方法对我来说非常有用,你只需像这样使用它: 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;
}
}
}
}
关于c# - 在 C# 中从 context.httprequest 读取原始数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16421961/