NancyFx 2.0的开源框架的使用-Forms

同样的像前面2篇博文一样,每个项目的开始基本都是建个空的Web项目

在NuGet库中安装以下几个NuGet包

  • Nancy
  • Nancy.Authentication.Forms
  • Nancy.Hosting.Aspnet
  • Nancy.ViewEngines.Razor

项目中同样分别建Module,Models,Views 三个文件夹,并在Module文件夹里面添加MainModule类

 public MainModule()
        {
            Get("/", Lexan => { return View["index"]; });
            Get("/login", Lexan =>
             {
                 dynamic model = new ExpandoObject();
                 model.Errored = this.Request.Query.error.HasValue;
                 return View["login",model];
              });
        }

接着往Models文件夹里面添加UserDatabase类

private static List<Tuple<string, string, Guid>> user = new List<Tuple<string, string, Guid>>();
        static UserDatabase()
        {
            //guid码是一个唯一的id,这个id可以自己另外写一个guid生成器去生成
            //登陆账号Lexan,密码是password
            user.Add(new Tuple<string, string, Guid>("Lexan","password",new Guid("87e516f4-c759-430d-a552-18ad8e65483b")));
        }
        public ClaimsPrincipal GetUserFromIdentifier(Guid identifier,NancyContext context)
        {
            //guid值赋给userRecord
            var userRecord = user.FirstOrDefault(x=>x.Item3==identifier);
            return userRecord == null ? null : new ClaimsPrincipal(new GenericIdentity(userRecord.Item1));
        }
        public static Guid? ValidateUser(string username,string password)
        {
            var usersRecord = user.FirstOrDefault(x=>x.Item1==username&&x.Item2==password);
            if (usersRecord==null)
            {
                return null;
            }
            return usersRecord.Item3;
        }

接着继续回到MainModule文件夹里面去写完类里面的post登陆方法和get登出方法

 Post("/login",Lexan=>
            {
                var userGuid = UserDatabase.ValidateUser((string)this.Request.Form.Username,(string)this.Request.Form.Password);
                if (userGuid==null)
                {
                    return this.Context.GetRedirect("~/login?error=true&username="+(string)this.Request.Form.Username);
                }
                DateTime? expiry = null;
                if (this.Request.Form.RememberMe.HasValue)
                {
                    expiry = DateTime.Now.AddDays(7);
                }
                return this.LoginAndRedirect(userGuid.Value,expiry);
            });
            //登出,并返回到主页
            Get("/logout",Lexan=> { return this.LogoutAndRedirect("~/"); });

继续往Module文件夹里面添加PartlySecureModule类,SecureModule类,以及Models文件里面添加UserModel类

 public PartlySecureModule():base("/partlysecure")
        {
            Get("/",Lexan=>"");
            Get("/secured",Lexan=>
            {
                this.RequiresAuthentication();
                //获取UserModel里面的Name值
                var model = new UserModel(this.Context.CurrentUser.Identity.Name);
                return View["secure.cshtml",model];
            });
        }

SecureModule类

  public SecureModule():base("/secure")
        {
            this.RequiresAuthentication();
            Get("/",Lexan=>
            {
                var model = new UserModel(this.Context.CurrentUser.Identity.Name);
                return View["secure.cshtml",model];
            });
        }

UserModel类

        public string Username { get; set; }
        public UserModel(string username)
        {
            Username = username;
        }

还有一个引导项目的FormsBootstrapper类,添加在根目录

        protected override void ConfigureApplicationContainer(TinyIoCContainer container)
        {
           // base.ConfigureApplicationContainer(container);
        }
        protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context)
        {
            base.ConfigureRequestContainer(container, context);
            //这里我们将用户映射器注册为每个请求的单一实例。
            //由于现在是每个请求, 我们可以注入一个请求范围
            //数据库 "上下文" 或其他请求范围的服务。
            container.Register<IUserMapper,UserDatabase>();
        }
        protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
        {
            //base.RequestStartup(container, pipelines, context);

            //在请求启动时, 我们修改请求管线
            //包括 forms 身份验证-在我们现在的请求中传递
            //作用域的用户名映射程序。
            //在这里传递的管道是特定于此请求的,
            //因此, 我们可以添加 / 删除 / 更新的项目, 如下所示。
            var formsAuthenConfiguration = new FormsAuthenticationConfiguration()
            {
                RedirectUrl="~/login",
                UserMapper=container.Resolve<IUserMapper>()
            };
            FormsAuthentication.Enable(pipelines,formsAuthenConfiguration);
        }

以上的后台逻辑是基本的写完了,接下里处理界面,在View是文件夹里面添加index,login,secure页面

页面就暂时这么处理,运行看看FormsDemo

最后的提醒别忘记里修改Web.config哦

这里声明一下,本来昨天博主要更新的,但是由于某些事情,没能及时更新

原文地址:https://www.cnblogs.com/R00R/p/6847357.html