操作筛选以检查会话MVC3

时间:2014-02-28 08:53:21

标签: asp.net-mvc-3 session

我想在我的应用程序中创建一些自定义过滤器

成功登录后,我会在会话中记录用户详细信息,并希望检查会话是否已过期(如果会话已过期,我想重定向到登录页面),我需要一个过滤器。

  public class MyActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        SchoolApp.ViewModels.CurrentSessionModel  model=(SchoolApp.ViewModels.CurrentSessionModel)HttpContext.Current.Session["mySession"];
        if (model == null)
        {
          //Redirect to Login page 
        }
        else
        {
            base.OnActionExecuting(filterContext);
        }
    }
}

但问题是,即使在加载登录页面时,这也会触发每个请求。那么我该如何制作一个有用的过滤器控件来检查会话

1 个答案:

答案 0 :(得分:1)

看起来你正试图在那里做错事。检查你的web.config文件 - 它应该有如下部分:

<authentication mode="Forms">
  <forms loginUrl="http://www.your_domain.com/login" name="cookie_name" defaultUrl="default_url" domain="your_domain" enableCrossAppRedirects="true" protection="All" slidingExpiration="true" cookieless="UseCookies" timeout="1440" path="/" />
</authentication>

如果您的会话已过期(已存在cookie_name的Cookie已不存在) - 用户将自动重定向到loginUrl

如果你仍然想使用过滤器 - 这个解决方案允许你排除一些控制器/动作的全局过滤器:

假设你在global.asax.cs中有方法:

private static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    IFilterProvider[] providers = FilterProviders.Providers.ToArray();
    FilterProviders.Providers.Clear();
    FilterProviders.Providers.Add(new ExcludeFilterProvider(providers));

    filters.Add(DependencyResolver.Current.GetService<MyFilter>(), 2); // add your global filters here
}

在global.asax.cs中调用它:

RegisterGlobalFilters(GlobalFilters.Filters);

过滤器提供程序类将如下所示:

public class ExcludeFilterProvider : IFilterProvider
{
    private readonly FilterProviderCollection _filterProviders;

    public ExcludeFilterProvider(IFilterProvider[] filters)
    {
        _filterProviders = new FilterProviderCollection(filters);
    }

    public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
    {
        Filter[] filters = _filterProviders.GetFilters(controllerContext, actionDescriptor).ToArray();
        if (filters.Select(f => f.Instance).OfType<OverrideExcludeFilter>().Any())
            return filters;
        IEnumerable<ExcludeFilterAttribute> excludeFilters = (from f in filters where f.Instance is ExcludeFilterAttribute select f.Instance as ExcludeFilterAttribute);
        var excludeFilterAttributes = excludeFilters as ExcludeFilterAttribute[] ?? excludeFilters.ToArray();
        if (excludeFilterAttributes.FirstOrDefault(f => f.AllFilters) != null)
        {
            return new Collection<Filter>();
        }

        var filterTypesToRemove = excludeFilterAttributes.SelectMany(excludeFilter => excludeFilter.FilterTypes);
        IEnumerable<Filter> res = (from filter in filters where !filterTypesToRemove.Contains(filter.Instance.GetType()) select filter);
        return res;
    }
}

ExcludeFilter属性类:

public class ExcludeFilterAttribute : FilterAttribute
{
    private readonly Type[] _filterType;

    public ExcludeFilterAttribute(bool allFilters)
    {
        AllFilters = allFilters;
    }

    public ExcludeFilterAttribute(params Type[] filterType)
    {
        _filterType = filterType;
    }

    /// <summary>
    /// exclude all filters
    /// </summary>
    public bool AllFilters { get; private set; }

    public Type[] FilterTypes
    {
        get
        {
            return _filterType;
        }
    }
}

使用示例:

    [ExcludeFilter(new[] { typeof(MyFilter) })]
    public ActionResult MyAction()
    {
        //some codes
    }

因此,这种类型为MyFilter的过滤器不会触发指定的操作