MVC 过滤器的使用

这几天项目中做了个过滤器 现在共享一下
/// <summary>
    /// 有登录入口的过滤器 继承此BaseController就可以了
    /// </summary>
    public class BaseController : Controller,IAuthorizationFilter
    {
        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result = new RedirectResult("/Home/Index");
            }
            else {
                filterContext.Result = new RedirectResult("/Login/Index");
            }
        }
    }
    /// <summary>
    /// 嵌入到别人的网站下无登录入口过滤器
    /// </summary>
    public class ValidateLogin : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
          //在判断IsAuthenticated前要在赋值 使用此方法就可以 FormsAuthentication.SetAuthCookie("testwty",false);
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary(new {controller ="Home",action="ErrorDemo"}));
            }
        }
    }
    //在Controller 中添加
    [ValidateLogin]属性就可以了
 
当然也可以在webconfig中添加
<authorization>
      <deny users="?"/>
    </authorization>
如果大家有更好的方法希望能共享一下

转载于:https://www.cnblogs.com/houziwty/archive/2011/12/01/2269907.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值