首页 新闻 赞助 找找看

mvc4里面怎样做登录过滤器?

0
[已解决问题] 解决于 2014-12-27 14:30

想做一个过滤器来验证用户是否登录,但是有两个区域,一个是Admin后台管理的、一个是网站首页游客浏览的不用登录。

在App_Start里的FilterConfig.cs会验证全局的吧,想问怎样只验证Admin这个区域里的controllers?

AaronLi的主页 AaronLi | 初学一级 | 园豆:41
提问于:2014-12-24 12:48
< >
分享
最佳答案
0

不是在全局里定义,你定义一个需要登记才能访问的Controller,如SignController

public class SignedController : ExceptionController
    {
        protected override void OnActionExecuting(ActionExecutingContext filterContext)

        {

              //在些判断用户是否已经登录,若未登录,则跳转到登录页面,同时把当前的url作为参数

              if(!login)

              {

string ReturnUrl = "/login.html?ReturnUrl=" + filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.Url.AbsoluteUri);
                //写代码跳转到登录页面
                return;

              }

        }

}

受保护页面的controller就可以继承此SignController

另外一种是使用拦截器,自定义一个拦截器,并在拦截器里进行判断,最后把拦截器 标注在需要先登录的 Action或controller上。

奖励园豆:5
king2003 | 初学一级 |园豆:161 | 2014-12-24 17:45

非常感谢你的回复和指导,谢谢。

AaronLi | 园豆:41 (初学一级) | 2014-12-27 14:30
其他回答(1)
0
    /// <summary> 
    /// 使用 FormsAuthentication 验证用户权限
    /// 验证失败则跳转到登录页面 
    /// </summary> 
    [RequiresAuthentication]
    public class RequiresAuthenticationAttribute : ActionFilterAttribute
    {

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            //redirect if not authenticated 
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {

                //use the current url for the redirect 
                string redirectOnSuccess = filterContext.HttpContext.Request.Url.AbsolutePath;

                //send them off to the login page 
                string redirectUrl = string.Format("?ReturnUrl={0}", redirectOnSuccess);
                string loginUrl = FormsAuthentication.LoginUrl + redirectUrl;
                filterContext.HttpContext.Response.Redirect(loginUrl, true);

            }
        }
    }

在定义一个basecontroller

    [RequiresAuthentication]
    public class BaseController : Controller
    {
        protected DataContext db = new DataContext();
        protected int PageSize { get { int ps; return Int32.TryParse(System.Web.Configuration.WebConfigurationManager.AppSettings["PageSize"], out ps) ? ps : 15; } }
    }

注意添加的[RequiresAuthentication]特性

然后让你的admin下的所有controller继承basecontroller

i迷倪 | 园豆:185 (初学一级) | 2014-12-25 19:08

非常感谢你的回复和指导,谢谢。

支持(0) 反对(0) AaronLi | 园豆:41 (初学一级) | 2014-12-27 14:30
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册