在 global.asax Application_BeginRequest 中添加动态参数

Add dynamic parameter in global.asax Application_BeginRequest

我正在阅读这个帖子:http://sandblogaspnet.blogspot.com/2008/03/methods-in-globalasax.html

我正在尝试在每个请求中发送额外信息(在 Application_BeginRequest 中)。是否可以在执行请求之前在此时添加一个新参数?

参数是自定义 guid(用于跟踪使用情况)和移动检测。

是的,这是可能的。一种可能的方法是将该信息存储在 HttpContext class 的 Items 字典中。这是来自 ASP.NET MVC 的 global.asax 文件中的示例实现:

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    { }

    protected void Application_BeginRequest(Object sender, EventArgs e)
    {
        HttpContext.Current.Items["CustomVariable"] = Guid.NewGuid();
    }
}       

在请求期间可以访问此信息,因此您可以稍后在您的控制器等中检索它。

如果您正在使用 ASP.NET MVC,您也可以使用 全局操作过滤器 来做类似的事情,并将其也注册到 global.asax 中。