授权过滤器在我的mvc项目中不起作用

时间:2016-01-06 08:51:48

标签: c# asp.net-mvc authentication filter

我是新手学习mvc中的过滤器。我在项目中创建了一个授权过滤器。

的AccountController

 public class AccountController : Controller
    {
        //
        // GET: /Account/

        public ActionResult Login()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Logins()
        {
            string username = Request["username"];
            string password = Request["password"];
            Session.Add("username", username);
            Session.Add("password", password);

            return Redirect("/Home");
        }

    }

    public class CustomAuthorizationAttribute : FilterAttribute, IAuthorizationFilter
    {  
        void IAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext)
        {
            try
            {
                string username = HttpContext.Current.Session["username"].ToString();
                string password = HttpContext.Current.Session["password"].ToString();

                if (username == password)
                {

                    HttpContext.Current.Response.Redirect("/Home");

                }
                else
                {

                    HttpContext.Current.Response.Redirect("/Account/login");
                }
            }
            catch
            {
                HttpContext.Current.Response.Redirect("/Account/login");
            }
        }

    }

的HomeController

public class HomeController : Controller
    {
        //
        // GET: /Home/
        [CustomAuthorization]
        public ActionResult Index()
        {

            return View();
        }

    }

但是现在我在运行这个项目时检查相同的字符串作为用户名和密码,如果用户名和密码正确,主页会一次又一次地重新加载。

1 个答案:

答案 0 :(得分:1)

从Authorization属性继承并覆盖默认行为 简单的实现就像这样

public class OptionalAuthorizeAttribute : AuthorizeAttribute
{

public OptionalAuthorizeAttribute()
{

}

protected override bool AuthorizeCore(HttpContext httpContext){
            string username = HttpContext.Current.Session["username"].ToString();
            string password = HttpContext.Current.Session["password"].ToString();

            if (username == password)
            {
                return true;
            }
                return base.AuthorizeCore(httpContext);
    }
}

然后你可以覆盖AuthorizeAttribute.HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext)的行为

旁注:我是用手机写的这个答案,所以请在粘贴到visual studio时仔细检查语法错误