假设你有一个名为Protected
(如控制器)视图文件夹,你有几个动作指向一些意见,我会做到这一点:
- 装点控制器/与行动筛选器操作,例如:
[SimpleMembership]
- 上行动过滤器,只检查是否存在和会话可变内容
- 如果没有正确的
重定向到一个
代码:
public class SimpleMembershipAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//redirect if not authenticated
if (filterContext.HttpContext.Session["myApp-Authentication"] == null ||
filterContext.HttpContext.Session["myApp-Authentication"] != "123")
{
//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 = "/Protected/SignIn" + redirectUrl;
filterContext.HttpContext.Response.Redirect(loginUrl, true);
}
}
}
和控制器
public class ProtectedController : Controller
{
[SimpleMembership]
public ActionResult Index()
{
return View();
}
public ActionResult SignIn()
{
return View();
}
[HttpPost]
public ActionResult SignIn(string pwd)
{
if (pwd == "123")
{
Session["myApp-Authentication"] = "123";
return RedirectToAction("Index");
}
return View();
}
}
,如果你想装饰整个controller
,你需要之外将SignIn
方法,以达到那里,你将需要认证。
的源代码:
可以下载简单MVC3解决方案http://cl.ly/JN6B或下跌随意查看GitHub的代码。
这正是我一直在寻找的,谢谢! – Zach