发布于 2016-06-06 02:07:52 | 128 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的精品教程,程序狗速度看过来!

ASP.NET

ASP.NET 是.NET FrameWork的一部分,是一项微软公司的技术,是一种使嵌入网页中的脚本可由因特网服务器执行的服务器端脚本技术,它可以在通过HTTP请求文档时再在Web服务器上动态创建它们。 指 Active Server Pages(动态服务器页面) ,运行于 IIS(Internet Information Server 服务,是Windows开发的Web服务器)之中的程序 。


在ASP.NET MVC中,通过使用其所提供的内置

[Authorize]
public ActionResult Index()

标记的方式,可以实现所标记的ACTION必须是认证用户才能访问;

通过使用

[Authorize(Users="username")]

的方式,可以实现所标记的ACTION必须是某个具体的用户才能访问,以上两种方式使用起来非常方便,在NeedDinner示例程序中已有具休的实现过程,

但是,我们在实际的应用中所使用的大都是基于角色(Roles)的认证方式,NeedDinner中却未给出,本文给出具体实现(基于ASP.NET Forms验证)过程:

step 1
在完成UserName和Password认证后,向客户端写入认证Cookie

代码


        FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
            1,
            userName,
            DateTime.Now,
            DateTime.Now.AddMinutes(20),
            false,
            "admin"//写入用户角色
            );

        string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

        System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
        System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);

step 2
在Global.asax.cs文件中加入以下代码,用于在用户登陆网站时读取Cookie

代码


protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
        HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
        if (authCookie == null || authCookie.Value == "")
        {
            return;
        }
        FormsAuthenticationTicket authTicket = null;
        try
        {
            authTicket = FormsAuthentication.Decrypt(authCookie.Value);
        }
        catch
        {
            return;
        }
        string[] roles = authTicket.UserData.Split(new char[] { ';' });
         if (Context.User != null)
        {
            Context.User = new System.Security.Principal.GenericPrincipal(Context.User.Identity, roles);
        }
    }

step 3

这样以来,就可以使用实现以下效果


  [Authorize(Roles="admin")]
    public ActionResult Index(int ? page)



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务