在执行任何操作之前执行代码 [英] Executing code before any action

查看:72
本文介绍了在执行任何操作之前执行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下要求:

在对我的网页的每个请求中,无论用户尝试执行哪种操作,我都需要调用一些代码来检查资源是否到位.如果是,那么一切都很好,应该正常调用action方法.

On every request to my web page, regardless of which action the user is trying to invoke, I need to call some code that checks if a resource is in place. If it is, then everything is fine and the action method should be called as normal.

但是,如果此资源不可用,我希望所有请求都返回一个单独的页面,要求用户从可用资源列表中选择另一个资源.

However, if this resource is not available, I want all requests to return a separate page asking the user to select another resource from a list of available ones.

那么是否有可能在任何可以取消对动作方法的调用的选项之前执行的动作方法之前运行一个方法呢?

So is it possible to have one method run before any action method that have the option of cancelling the call to the action method, and doing something else instead?

推荐答案

查看全局操作过滤器(自asp.net mvc 3起可用):

Look at global action filters (available since asp.net mvc 3): http://msdn.microsoft.com/en-us/library/gg416513%28v=vs.98%29.aspx

基本上,在您的Global.asax中,您可以在应用程序启动期间(在Application_Start()中)通过以下方式全局注册过滤器:

Basically, in your Global.asax, you can register the filter globally during your application startup (in Application_Start()) with:

GlobalFilters.Filters.Add(new MyActionFilterAttribute());

然后,您可以覆盖OnActionExecuting方法,并使用RedirectToRouteResult设置Result属性.

You can then override the OnActionExecuting method, and set the Result property with a RedirectToRouteResult.

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
    if (IsMyResourceAvailable())
    {
        filterContext.Result = new RedirectToRouteResult(
            new RouteValueDictionary {
                { "Controller", "YourControllerName" },
                { "Action", "YourAction" } 
            });
    }

    base.OnActionExecuting(filterContext);
}

这篇关于在执行任何操作之前执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆