加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

ASP.Net MVC 3 – 密码保护视图

发布时间:2020-12-16 07:35:02 所属栏目:asp.Net 来源:网络整理
导读:Visual Studio 2010 – MVC 3 我有一个asp.net mvc应用程序的管理部分,我想限制访问.应用程序不会使用帐户,因此我不会使用管理员角色或用户来授权访问权限. 我希望通过输入单个密码来访问该部分.本节将介绍一些操作.我已经设置了一个管理控制器,它可以重定向
Visual Studio 2010 – MVC 3

我有一个asp.net mvc应用程序的管理部分,我想限制访问.应用程序不会使用帐户,因此我不会使用管理员角色或用户来授权访问权限.

我希望通过输入单个密码来访问该部分.本节将介绍一些操作.我已经设置了一个管理控制器,它可以重定向到许多不同的视图,因此基本上任何需要限制该控制器控制的视图.

我也希望它只需要为会话输入一次密码,因此当浏览器关闭并重新打开时,需要重新输入密码.

我怎么做到这一点?

解决方法

假设您有一个名为Protected的View文件夹(作为您的控制器),并且您有几个指向多个Views的Actions,我会这样做:

>使用动作过滤器装饰控制器/动作,例如:[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);
        }
    }
}

和你的控制器

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

如果你想装饰整个控制器,你需要将SignIn方法移到外面以便到达那里,你需要进行身份验证.

源代码:

您可以下载简单的MVC3解决方案http://cl.ly/JN6B或免费查看GitHub上的代码.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读