您的位置:首页 > 编程语言 > ASP

ASP.NET MVC 3–Global Action Filters

2013-01-23 23:06 495 查看
public class MvcProfilerGlobalAttribute : ActionFilterAttribute
{
//...
}

protected void Application_Start()
{
//...
GlobalFilters.Filters.Add(new MvcProfilerGlobalAttribute());
}

public class MvcProfilerGlobalAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var httpContext = filterContext.RequestContext.HttpContext;
var httpRequest = httpContext.Request;
var inputStream = httpRequest.InputStream;
var requestBody = new StreamReader(inputStream).ReadToEnd();
inputStream.Seek(0, SeekOrigin.Begin);
}

public class ProfileData
{
public string Url { get; set; }
public string RequestData { get; set; }
public string ResponseHttpStatusCode { get; set; }
public string RequestHeaders { get; set; }
public string ResponseHeaders { get; set; }
public string QueryStringData { get; set; }
public string ClientIp { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
}
public class ProfilerContext : IDisposable
{
private readonly IProfilerLogRepository repository;
private const string ProfilerItemKey = "DEVELOQPROFILER";
private readonly Guid profilerContextIdentifier;
private readonly DateTime started;

public ProfileData ProfileData { get; private set; }

public ProfilerContext() : this(new InMemoryProfilerLogRepository()) { }

public ProfilerContext(IProfilerLogRepository repository)
{
this.repository = repository;
profilerContextIdentifier = Guid.NewGuid();
started = DateTime.UtcNow;
ProfileData = new ProfileData();
}

public void Persist()
{
repository.Add(ProfileData);
}

public void Dispose()
{
Persist();
}

public static ProfilerContext Current
{
get
{
var context = HttpContext.Current;
if (context == null) return null;
InitCurrentProfiler();
return context.Items[ProfilerItemKey] as ProfilerContext;
}
private set
{
var context = HttpContext.Current;
if (context == null) return;

context.Items[ProfilerItemKey] = value;
}
}

private static void InitCurrentProfiler()
{
var context = HttpContext.Current;
if (context == null) return;
if (context.Items[ProfilerItemKey] as ProfilerContext != null) return;

Current = new ProfilerContext();
}

}

public interface IProfilerLogRepository
{
void Add(ProfileData profileData);
List<profiledata> GetAll();
}
public class InMemoryProfilerLogRepository : IProfilerLogRepository
{
private static List<profiledata> profileLogs;

public InMemoryProfilerLogRepository()
{
if (profileLogs == null)
profileLogs = new List<profiledata>();
}

public void Add(ProfileData profileData)
{
profileLogs.Add(profileData);
}

public List<profiledata> GetAll()
{
return profileLogs;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: