对 ASP.NET MVC 中的每个请求执行代码
我有一个所有控制器都继承自的控制器,我需要为每个控制器请求执行一些代码。 我尝试了以下操作:
protected override void Execute(System.Web.Routing.RequestContext requestContext)
{
if (Session["mallDetected"] == null)
{
Session["mallDetected"] = DateTime.Now.Ticks;
IList<Mall> malls = Mall.FindNearestByIp(Request.UserHostAddress);
if (malls.Count > 0)
{
Session["mall"] = malls[0];
}
}
base.Execute(requestContext);
}
但显然,在调用 base.Execute() 之前,执行方法中的会话状态不可用,这对我不起作用。 是否有地方可以为 ASP.NET MVC 中的每个请求执行此会话代码?
I have a controller that all my controllers inherit from and I need to execute some code for every controller request. I tried the following:
protected override void Execute(System.Web.Routing.RequestContext requestContext)
{
if (Session["mallDetected"] == null)
{
Session["mallDetected"] = DateTime.Now.Ticks;
IList<Mall> malls = Mall.FindNearestByIp(Request.UserHostAddress);
if (malls.Count > 0)
{
Session["mall"] = malls[0];
}
}
base.Execute(requestContext);
}
But apparently session state isn't available in the Execute method until AFTER the call to base.Execute(), which doesn't work for me. Is there a place where I can execute this session code for each request in ASP.NET MVC?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试重写基本控制器中的
OnActionExecuted
或将功能实现为过滤器。Try overriding
OnActionExecuted
in the base controller or implementing the functionality as a filter.如果您希望 ASP.NET 应用程序在每次请求时都发生一些事情,那么最好将其构建到 IHttpModule 中,而不是将其构建到控制器中。 您如何保证您的继任者能够正确实施您的控制器?
If you want something to happen in an ASP.NET application on every request, you are probably better off building it into an IHttpModule rather than building it into a controller. How do you guarantee your successor will implement your controller correctly?