【发布时间】:2015-05-21 11:10:45
【问题描述】:
所以我的项目需求发生了变化,现在我认为我需要构建自己的操作过滤器。
所以,这是我当前的登录控制器:
public class LoginController : Controller
{
// GET: Login
public ActionResult Index()
{
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginViewModel model)
{
string userName = AuthenticateUser(model.UserName, model.Password);
if (!(String.IsNullOrEmpty(userName)))
{
Session["UserName"] = userName;
return View("~/Views/Home/Default.cshtml");
}
else
{
ModelState.AddModelError("", "Invalid Login");
return View("~/Views/Home/Login.cshtml");
}
}
public string AuthenticateUser(string username, string password)
{
if(password.Equals("123")
return "Super"
else
return null;
}
public ActionResult LogOff()
{
Session["UserName"] = null;
//AuthenticationManager.SignOut();
return View("~/Views/Home/Login.cshtml");
}
}
这是我的动作过滤器尝试:
public class AuthorizationFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (HttpContext.Current.Session["UserName"] != null)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary{{ "controller", "MainPage" },
{ "action", "Default" }
});
}
base.OnActionExecuting(filterContext);
}
}
我已经将它添加到 FilterConfig,但是当我登录时它不会加载 Default.cshtml,它只是不断循环操作过滤器。它的操作结果如下所示:
//这个位于MainPage控制器中
[AuthorizationFilter]
public ActionResult Default()
{
return View("~/Views/Home/Default.cshtml");
}
那么,我需要添加什么才能授予授权,以便只有经过身份验证的用户才能查看应用程序的页面?我应该使用会话变量还是有另一种/更好的方法来使用?我几乎坚持使用 AuthenticateUser(),因为现在发生的只是一个简单的比较,就像我们现在的比较。
感谢您的宝贵时间。
【问题讨论】:
-
澄清一下,您已将
AuthorizationFilter添加到 FilterConfig 中? -
@WillSmith 是的,我将它添加到 FilterConfig
-
为什么不能在控制器上使用内置的
[Authorize]属性? -
@Coulton 当我的 AuthenticateUser 看起来像这样时,我该如何使用?严肃的问题,根据我在这种情况下所读到的内容,我必须建立自己的。
-
不创建标准FilterAttribute,而是将其创建为
AuthorizationAttributemsdn.microsoft.com/en-us/library/ee707357%28v=vs.91%29.aspx
标签: c# asp.net asp.net-mvc asp.net-mvc-4