C#ASP.NET MVC:如何阻止方法的重写?

C#ASP.NET MVC:如何阻止方法的重写?,c#,asp.net,session,web,model-view-controller,C#,Asp.net,Session,Web,Model View Controller,我正在为我的项目创建会话控件,目前我需要帮助 基本上,我的HomeController继承自CustomController HomeController管理方法,并在方法之前运行CustomController以检查会话信息 public class HomeController : CustomController { public ActionResult Index() { } } public class CustomCo

我正在为我的项目创建会话控件,目前我需要帮助

基本上,我的
HomeController
继承自
CustomController

HomeController
管理方法,并在方法之前运行
CustomController
以检查会话信息

public class HomeController : CustomController
{
     public ActionResult Index()
     {                
     }
}

public class CustomController : Controller
{
    public OnActionExecuting()
    {
       // Check session
    }
}

我的问题是,我不想在
HomeController/Index
方法之前检查
Session
。这是可能的吗?

您可以使用自定义属性类执行此操作,如下所示:

/// <summary>
/// Indicates whether session checking is enabled for an MVC action or controller.
/// </summary>
public class CheckSessionAttribute : Attribute
{
    public CheckSessionAttribute(bool enabled)
    {
        this.Enabled = enabled;
    }

    public bool Enabled { get; }
}

这将检查是否存在
[CheckSession(false)]
属性,并在这种情况下禁用会话检查。通过这种方式,您可以通过使用新属性对不应检查会话信息的方法进行注释来配置这些方法。这也立即清楚地表明,没有检查会话的特定操作。

publicstaticstringindex()
不是操作方法
OnActionExecuting
在索引方法之前不要执行对不起,我已经更新了问题。非常感谢。(其ActionResult)正确的签名是
受保护的覆盖无效OnActionExecuting(ActionExecutionContext filterContext
查看以了解如何在
OnActionExecuting
中获取控制器名称和操作名称,并使用它跳过会话检查。这当然是我要找的。比你多得多!
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
    // Check if the CheckSession attribute is present and skip the session 
    // check if [CheckSession(false)] was explicitly provided.
    bool checkSession = filterContext.ActionDescriptor.GetCustomAttributes(typeof(CheckSession), true)
        .OfType<CheckSession>()
        .Select(attr => attr.Enabled)
        .DefaultIfEmpty(true)
        .First();

    if (checkSession) 
    {
        // Check session
    }
}