wil*_*ink 2 c# xml post http request
我已经多次看过这个话题,但没有一个解决方案对我有帮助,我不知道为什么没有任何作用.
我有一个C#web部分,我只是想读取http post请求的数据内容.在请求中有一些xml,但是当我尝试在Web部分中读取它时,这不会显示出来.它只给我标题数据和一些服务器变量.
我正在尝试阅读的请求是通过Chrome的Simple Rest扩展提交的.当我用fiddler监视时,我可以看到请求,当我点击TextView时,我可以看到所有的XML都没有问题.那么为什么它不显示在服务器上?
我尝试使用Context.Request.SaveAs(),但似乎只给我标题数据.我也尝试循环遍历Context.Request.Params并打印每个参数,但它们都不包含xml.
最后,我尝试使用读取请求的内容
Context.Request.ContentEncoding
.GetString(Context.Request.BinaryRead(Context.Request.TotalBytes))
Run Code Online (Sandbox Code Playgroud)
并且
string strmContents = "";
using (StreamReader reader = new StreamReader(Context.Request.InputStream))
{
while (reader.Peek() >= 0)
{
strmContents += reader.ReadLine();
}
}
Run Code Online (Sandbox Code Playgroud)
但这两种方法都会导致空字符串.
让我感到困惑(并加剧)的是,如果我查看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;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4818 次 |
| 最近记录: |