以下代码在Global.asax中用于记录错误是ASP.NET MVC3应用程序。
有些错误与从PostgreSql服务器读取数据的超时有关。
如何向此添加请求持续时间记录? 是否有一些propaerty在MVC3中提供请求开始时间?
我在
中查看了样本http://www.codeproject.com/Articles/550510/Exception-Handling-and-NET
http://msdn.microsoft.com/en-us/library/24395wz3(v=vs.100).aspx
Global.asax - Application_Error - How can I get Page data?
但还没有找到这样的样本。
void Application_Error(object sender, EventArgs e)
{
var sb = new StringBuilder();
var url = HttpContext.Current.Request.Url;
sb.AppendLine("Url " + url.ToString());
foreach (var d in Request.Form.AllKeys)
sb.AppendLine(d.ToString() + ":" + Request.Form[d].ToString());
sb.AppendLine();
foreach (var d in Request.Headers.AllKeys)
sb.AppendLine(d.ToString() + "\t" + Request.Headers[d].ToString());
Exception exception = Server.GetLastError();
MyLogger.WriteException(exception, "Application_Error", sb.ToString());
}
答案 0 :(得分:1)
您可以在配置文件
中添加此类路径的请求持续时间<location path="your path here">
<system.web>
<httpRuntime executionTimeout="600" />
</system.web>
或者您也可以将其设置到控制器中
HttpContext.Server.ScriptTimeout = timeout value here;
答案 1 :(得分:1)
如果要求您提出HTTP请求,可以将Application_BeginRequest和Application_EndRequest与ThreadStatic Stopwatch结合使用,如下所示:
public class MvcApplication : System.Web.HttpApplication
{
[ThreadStatic]
private static Stopwatch stopwatch;
protected void Application_Start()
{
//...
}
protected void Application_BeginRequest()
{
stopwatch = new Stopwatch();
stopwatch.Start();
}
protected void Application_EndRequest()
{
stopwatch.Stop();
var elapsedTime = stopwatch.ElapsedMilliseconds;
//log time...
stopwatch.Reset();
}
}
在您的情况下,您可以使用
而不是Application_EndRequestprotected void Application_Error(object sender, EventArgs e)
{
//...
stopwatch.Stop();
var time = stopwatch.ElapsedMilliseconds;
stopwatch.Reset();
//...
}
当ThreadStatic:look here时,您应该注意一些问题 。如果您不想使用ThreadStatic,可以像这样使用HttpContext.Current.Items:
protected void Application_BeginRequest()
{
var stopwatch = new Stopwatch();
stopwatch = new Stopwatch();
stopwatch.Start();
HttpContext.Current.Items.Add("RequestStopwatch", stopwatch);
}
protected void Application_Error(object sender, EventArgs e)
{
//...
if (HttpContext.Current.Items["RequestStopwatch"] != null)
{
var stopwatch = (Stopwatch)HttpContext.Current.Items["RequestStopwatch"];
stopwatch.Stop();
var time = stopwatch.ElapsedMilliseconds;
//log time...
HttpContext.Current.Items.Remove("RequestStopwatch");
}
//...
}
答案 2 :(得分:0)
你自己计时。在BeginRequest处理程序中,启动秒表,然后将其保存到HttpContext.Items。然后在错误处理程序中,将其取回并停止它。定时整个请求的方法相同,只有你在EndRequest中执行停止部分。
看看这个example,这是一个http模块,它会将请求添加到repsonse。