【发布时间】:2011-01-07 20:56:39
【问题描述】:
我对 .net 有点陌生,并试图掌握一些概念。
我已经在 Coldfusion 中写了一段时间了,在 CF 中,Application.cfc 下有一个名为 onRequest() 的事件,每次有页面时都会触发。
.net 中的什么是用来捕获请求信息的?
此外,有没有办法锁定或扩展 Request 事件来触发我自己的事件?
【问题讨论】:
标签: asp.net .net asp.net-mvc asp.net-mvc-3
我对 .net 有点陌生,并试图掌握一些概念。
我已经在 Coldfusion 中写了一段时间了,在 CF 中,Application.cfc 下有一个名为 onRequest() 的事件,每次有页面时都会触发。
.net 中的什么是用来捕获请求信息的?
此外,有没有办法锁定或扩展 Request 事件来触发我自己的事件?
【问题讨论】:
标签: asp.net .net asp.net-mvc asp.net-mvc-3
您还可以找到 global.asax 文件并使用 HttpApplication 类的事件之一(例如 BeginRequest):
http://msdn.microsoft.com/en-us/library/system.web.httpapplication.aspx
HttpApplication 具有 Request 属性。
您可以在那里捕获每个请求,不仅与控制器相关(图像、css、错误地址)。
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_BeginRequest(object sender, EventArgs e)
{
//Request.Have_fun
}
}
如果你不想在 global.asax 文件中写代码,你应该考虑使用HttpModule。
使用此示例代码创建新类:
using System;
using System.Web;
namespace MyProject
{
public class MyHttpModule : IHttpModule
{
public void Init(HttpApplication application)
{
application.BeginRequest += ApplicationBeginRequest;
application.EndRequest += ApplicationEndRequest;
}
private void ApplicationEndRequest(object sender, EventArgs e)
{
//do something here with HttpContext.Current.Request
}
private static void ApplicationBeginRequest(Object source, EventArgs e)
{
//do something here with HttpContext.Current.Request
}
public void Dispose()
{
}
}
}
在 web.config 中添加两个条目(注册 HttpModule):
<system.web>
<httpModules>
<add name="MyHttpModule" type="MyProject.MyHttpModule" />
</httpModules>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="MyHttpModule" type="MyProject.MyHttpModule" />
</modules>
</system.webserver>
由于 IIS7 的变化(添加 system.webServer 部分),您必须在 web.config 中添加两个条目。
【讨论】:
OnActionExecuting 或其他答案建议的操作过滤器是更好的方法。
您可能会想要类似OnActionExecuting 的东西,它被称为before动作被击中。
要访问当前请求,您可以执行以下操作:
protected virtual void OnActionExecuting(ActionExecutingContext filterContext) {
//Do the default OnActionExecuting first.
base.OnActionExecuting(filterContext);
//The request variable will allow you to see information on the current request.
var request = filterContext.RequestContext.HttpRequest;
}
如果您想在每个控制器中访问它,那么您可能应该创建一个基本控制器并将其添加到那里。
public class BaseController : Controller
{
//Code above
}
在你的 Home 控制器中:
public class HomeController : BaseController
{
}
【讨论】:
如果您在 ASP.NET MVC 3 中工作,我建议您使用全局操作过滤器(每个要处理的“事件”使用一个),而不是直接进入 ASP.NET 应用程序/请求堆栈。
【讨论】: