Visual Studio 2010 - MVC 3
我有一个 asp.net mvc 应用程序的管理部分,我想限制对它的访问。例如,该应用程序不会使用帐户,因此我不会使用管理员角色或用户来授权访问。
我希望通过输入单个密码可以访问该部分。本节将有许多操作。我已经设置了一个管理 Controller ,它重定向到许多不同的 View ,所以基本上这个 Controller 控制的任何 View 都需要受到限制。
我也希望这样,一次 session 只需输入一次密码,因此当浏览器关闭并重新打开时,需要重新输入密码。
我将如何实现这一目标?
最佳答案
假设您有一个名为 Protected
的 View 文件夹。 (作为您的 Controller ),并且您有几个指向多个 View 的操作,我会这样做:
[SimpleMembership]
SignIn
如果不是正确的 在代码中:
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);
}
}
}
和你的 Controller
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 上的代码.
关于ASP.Net MVC 3 - 密码保护 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12378445/