操作筛选器以检查会话MVC3 [英] Action Filter to check Session MVC3

查看:57
本文介绍了操作筛选器以检查会话MVC3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to create some custom Filters in my application

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

After successful login i keep logged in user details in a session and want to check the session is expired or not ( If session expired i want to redirect to login page) and i need a filter for this.

  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);
        }
    }
}

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

But the problem is this will fire for every rquests even while loading Login page . So how can i make a useful filter control that check for session

推荐答案

看起来您在尝试做错事.检查您的web.config文件-它应具有以下部分:

Looks like you're trying to do wrong things there. Check your web.config file - it should have section like:

<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

If your session is expired (cookie with cookie_name non exists anymore) - user will be automatically redirected to loginUrl

如果您仍然想使用过滤器-有一种解决方案可以让您排除某些控制器/操作的全局过滤器:

If you still want to use filters - there's solution that allows you to exclude global filter for some controllers/actions:

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

assuming you have method in 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中调用它:

Call it in your global.asax.cs:

RegisterGlobalFilters(GlobalFilters.Filters);

过滤器提供程序类如下:

Filter provider class will look like:

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属性类:

ExcludeFilter attribute class:

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类型的过滤器将不会针对指定的操作触发

So this way your filter of type MyFilter won't fire for specified action

这篇关于操作筛选器以检查会话MVC3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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