【问题标题】:Authorization filter not working in my mvc project授权过滤器在我的 mvc 项目中不起作用
【发布时间】:2016-04-10 07:06:57
【问题描述】:

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

账户控制者

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

    }

家庭控制器

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

            return View();
        }

    }

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

【问题讨论】:

  • 如果用户名和密码正确,那么它将在 homecontroller 中加载索引(默认操作)操作,因为您编写了 HttpContext.Current.Response.Redirect("/Home");
  • 但它不去首页索引。重定向循环中的主页。
  • 这是故意的吗? '如果(用户名 == 密码)'
  • 我只是在检查,将来我会更改此代码。

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


【解决方案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时请仔细检查语法错误

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-12
    • 2015-09-09
    • 1970-01-01
    • 2012-07-14
    • 1970-01-01
    • 2019-01-31
    相关资源
    最近更新 更多