您还可以通过将代码放置在Global.asax.cs中来实现。
protected void Application_BeginRequest(object sender, EventArgs e)
{
byte[] inputStream = new byte[HttpContext.Current.Request.ContentLength];
HttpContext.Current.Request.InputStream.Read(inputStream, 0, inputStream.Length);
HttpContext.Current.Request.InputStream.Position = 0;
string requestString = ASCIIEncoding.ASCII.GetString(inputStream);
}
我有一个实用方法在我的 Web 服务中,当发生我没有预料到的情况,比如未处理的异常,我会使用它来捕获请求。
internal static void CaptureRequest()
{
const string procName = "CaptureRequest";
try
{
log.WarnFormat("{0} - Writing XML request to FailedSubmission folder", procName);
byte[] inputStream = new byte[HttpContext.Current.Request.ContentLength];
Int64 currentStreamPosition = HttpContext.Current.Request.InputStream.Position;
HttpContext.Current.Request.InputStream.Position = 0;
HttpContext.Current.Request.InputStream.Read(inputStream, 0, HttpContext.Current.Request.ContentLength);
HttpContext.Current.Request.InputStream.Position = currentStreamPosition;
string xml = ASCIIEncoding.ASCII.GetString(inputStream);
string fileName = Guid.NewGuid().ToString() + ".xml";
log.WarnFormat("{0} - Request being written to filename: {1}", procName, fileName);
File.WriteAllText(Configuration.FailedSubmissionsFolder + fileName, xml);
}
catch
{
}
}
然后在 web.config 文件中,我存储了几个 AppSetting 值,用于定义我想要使用哪个级别来捕获请求。
<!-- true/false - If true will write to an XML file the raw request when any Unhandled exception occurrs -->
<add key="CaptureRequestOnUnhandledException" value="true"/>
<!-- true/false - If true will write to an XML file the raw request when any type of error is returned to the client-->
<add key="CaptureRequestOnAllFailures" value="false"/>
<!-- true/false - If true will write to an XML file the raw request for every request to the web service -->
<add key="CaptureAllRequests" value="false"/>
然后在我的 Application_BeginRequest 中,我对它进行了修改。请注意,Configuration 是我创建的静态类,用于读取 web.config 和其他区域的属性。
protected void Application_BeginRequest(object sender, EventArgs e)
{
if(Configuration.CaptureAllRequests)
{
Utility.CaptureRequest();
}
}