MVC3 角色管理|MVC3权限设计

View:

 

@using (Html.BeginForm()) {
    <div>
        <fieldset>
            <legend>帐户信息</legend>

            <div class="editor-label">
                @Html.LabelFor(m => m.LoginID)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(m => m.LoginID)
                @Html.ValidationMessageFor(m => m.LoginID)
            </div>

            <div class="editor-label">
                @Html.LabelFor(m => m.LoginPwd)
            </div>
            <div class="editor-field">
                @Html.PasswordFor(m => m.LoginPwd)
                @Html.ValidationMessageFor(m => m.LoginPwd)
            </div>

            @*<div class="editor-label">
                @Html.CheckBoxFor(m => m.RememberMe)
                @Html.LabelFor(m => m.RememberMe)
            </div>*@

            <p>
                <input type="submit" value="登录" />
            </p>
        </fieldset>
    </div>
}

 

Controller:

 

[HttpPost]
        public ActionResult LogOn(Octopus.Monitor.Storage.Model.UserInfo model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                //自定义方法,检查登录用户是否存在
DataSet dataSet
= Octopus.Monitor.Storage.Mysql.DAL.UserInfoDAL.CheckUser(model); if (dataSet.Tables.Count > 0 && dataSet.Tables[0].Rows.Count > 0) { //如果存在,则根据用户ID去查询用户的角色,然后将角色类型存放于FormsAuthenticationTicket
DataSet roleDataSet
= Octopus.Monitor.Storage.Mysql.DAL.R_UserInfo_Role.GetUserRole(Convert.ToInt32(dataSet.Tables[0].Rows[0]["ID"])); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, model.LoginID, DateTime.Now, DateTime.Now.Add(FormsAuthentication.Timeout), true, roleDataSet.Tables[0].Rows[0]["RoleID"].ToString() ); HttpCookie cookie = new HttpCookie( FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket)); Response.Cookies.Add(cookie); if (!String.IsNullOrEmpty(returnUrl)) return Redirect(returnUrl); else return RedirectToAction("Index", "Home"); } else { ModelState.AddModelError("", "提供的用户名或密码不正确。"); } } // 如果我们进行到这一步时某个地方出错,则重新显示表单 return View(model); }

 

Global.asax:

public override void Init()
{
    AuthorizeRequest += new EventHandler(MvcApplication_AuthorizeRequest);
}
protected void MvcApplication_AuthorizeRequest(object sender, EventArgs e)
{
    FormsIdentity formIdentity = null;
    var identity = Context.User.Identity;
    if (identity != null)
        formIdentity = identity as FormsIdentity;
    if (formIdentity != null && formIdentity.IsAuthenticated)
    {
        var roles = formIdentity.Ticket.UserData.Split(',');
        Context.User = new GenericPrincipal(formIdentity, roles);
    }
}

 

 

 

posted on 2013-04-12 08:42  。!  阅读(339)  评论(0编辑  收藏  举报