在MVC中手工添加Form验证记录

VS2015用向导生成的MVC代码是自带一个AccountControl的和ManagerControl,但是对应的类和我原来数据库的数据不匹配,自带不记录手机号、电子邮件地址等,就想弄一个简单的自用,而且能和系统原来的数据结合。参考该博客,感谢原作者。下面记录一下步骤。
用向导生成一个不带Form验证的MVC页面(生成带Form验证的我暂时没改成功,太复杂了,也暂时不需要那么多)。

  1. web.config中添加验证
 <system.web>
   <authentication mode="Forms">
     <forms loginUrl="~/Account/Login" defaultUrl="~/Home/Index" protection="All" />
   </authentication>
   .....
   .....
 </system.web>
  1. 增加相应模型
    Models目录下增加以下3个模型
    LoginViewModel
    public class LoginViewModel
    {
        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "密码")]
        public string Password { get; set; }

        [Display(Name = "记住我?")]
        public bool RememberMe { get; set; }

        [Required]
        [Display(Name = "用户名")]
        public string UserName { get; set; }
    }

User

    public class User
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Password { get; set; }
        public string[] Roles { get; set; }
    }

UserRepository

        public bool ValidateUser(string name, string password)
        {
            Mydata data= new Mydata(name);//这里是自己原始数据库的数据
            if (stu == null) return false;
            if (stu.Password != password) return false;
            else return true;
        }

        public string[] GetRoles(string userName)
        {
            return new string[] { };//我的原始数据没有这一项,返回空数组
        }

        public User GetByStunumAndPassword(string name, string password)
        {
            Mydata data= new Mydata(name);//这里是自己原始数据库的数据
            if (data== null) return null;
            if (data.Password != password) return null;
            else
            {
                User usr= new User();
                usr.ID = data.Id;
                usr.Name = data.Name;
                usr.Password = data.Password;
                usr.Roles = new string[] { };
                return usr;
            }
        }
  1. 增加验证事件
    修改Global.asax
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
//以下为新增部分
        public MvcApplication()
        {
            AuthenticateRequest += new EventHandler(MvcApplication_AuthorizeRequest);
        }

        void MvcApplication_AuthorizeRequest(object sender, EventArgs e)
        {
            if (Context.User != null)//参考博客中没有这一句,但是我生成后会报错,所以加了这句,如果有人知道原因麻烦留言
            {
                IIdentity id = Context.User.Identity;
                if (id.IsAuthenticated)
                {
                    var roles = new Models.UserRepository().GetRoles(id.Name);
                    Context.User = new GenericPrincipal(id, roles);
                }
            }
        }
    }
  1. 增加相应的AccountControl控制器和视图
    这一部分都是抄作业了。
    控制器
public class AccountController : Controller
    {
        private UserRepository repository = new UserRepository();

        /*public AccountController()
        {
        }*/

        public ActionResult Login(string returnUrl)
        {
            ViewBag.returnUrl = returnUrl;
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (repository.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (!String.IsNullOrEmpty(returnUrl)) return Redirect(returnUrl);
                    else return RedirectToAction("About", "Home");
                }
                else
                    ModelState.AddModelError("", "用户名或密码不正确!");
            }
            return View(model);
        }

        //
        // POST: /Account/LogOff
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }
    }

视图

@using StudentMVCWithoutAuth.Models
@model LoginViewModel
@{
    ViewBag.Title = "登录";
}

<h2>@ViewBag.Title。</h2>
<div class="row">
    <div class="col-md-8">
        <section id="loginForm">
            @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
            {
                @Html.AntiForgeryToken()
                <h4>使用本地帐户登录。</h4>
                <hr />
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                <div class="form-group">
                    @Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" })
                    <div class="col-md-10">
                        @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
                        @Html.ValidationMessageFor(m => m.UserName, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="form-group">
                    @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
                    <div class="col-md-10">
                        @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
                        @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <div class="checkbox">
                            @Html.CheckBoxFor(m => m.RememberMe)
                            @Html.LabelFor(m => m.RememberMe)
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <input type="submit" value="登录" class="btn btn-default" />
                    </div>
                </div>
            }
        </section>
    </div>
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
  1. 引用中添加Microsoft.AspNet.Identity.Core
    直接用NuGet搜索Microsoft.AspNet.Identity.Core然后添加到项目中。

先写那么多,继续测试,如果发现bug,再改本文。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值