如何在其上添加角色和成员资格? [英] How can I add role and membership on it?

查看:74
本文介绍了如何在其上添加角色和成员资格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目中有registartion和登录表单,用户可以重新登录和登录。我创建了用户模块,视图和控制器。当我尝试添加角色并尝试使用intialzie会员时,我遇到了问题。我需要为用户和管理员添加一个角色。我该怎么做?比你的帮助更多



//在我的模式中我有

I have registartion and login form in my project for the user can registor and log in. I have cretaed user module, view, and controller.I have faced a problem when I tried to add role on it and try to intialzie membership. I need to add a role for user and adminstrator. how do i do it? than you for your help

// in my modeule I have

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace BootstrapPager.Models
{
    public class User
    {
        [Required]
        public virtual int Id { get; set; }
        [Required]
        [Display(Name = "First Name")]
        public virtual string FirstName { get; set; }
        [Required]
        [Display(Name = "Last Name")]
        public virtual string LastName { get; set; }
        [Required]
        [Display(Name = "Username")]
        public virtual string UserName { get; set; }

        [Required]
        [Display(Name = "Email Address")]
        [DataType(DataType.EmailAddress)]
        [RegularExpression("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$", ErrorMessage = "Please enter a valid Email Address")]
        public virtual string Email { get; set; }

        [Required]
        [DataType(DataType.Password)]
        public virtual string Password { get; set; }

        [Required]
        [NotMapped]
        [Display(Name = "Confirm Password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
        [Required]
        [Display(Name = "Address")]
        public string Address { get; set; }

        [Required]
        [Display(Name = "Country")]
        public string Country { get; set; } 
         [Required]
        [Display(Name = "City")]
        public string City { get; set; }
         [Required]
        [Display(Name = "State")]
        public string State { get; set; }
         [Required]
        [Display(Name = "Zip")]
        public string Zip { get; set; }





        
        //public virtual ICollection<RSVP> RSVPs { get; set; }
    }

    public class Login
    {
        [Required]
        [Display(Name = "Username")]
        public string UserName { get; set; }

        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }
    }


}




// in my conroller
<pre lang="c#">using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BootstrapPager.Models;
using Microsoft.VisualBasic;

namespace BootstrapPager.Controllers
{
    public class UserController : Controller
    {
        private EmployeeDb db = new EmployeeDb();

        //
        // GET: /User/

        public ActionResult Index()
        {
            return View(db.Users.ToList());
        }

        //
        // GET: /User/Details/5

        public ActionResult Details(int id = 0)
        {
            User user = db.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        //
        // GET: /User/Create
        
        public ActionResult Create()
        {
            //if (Session["user"] != null)
            //{
                
            //    return View();
            //}
            //else { return Content("Please Login First"); }
            return View();
        }

        //
        // POST: /User/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(User user)
        {
            if (ModelState.IsValid)
            {
                //User users = (User)db.Users.Where((a => a.Email == user.Email) || );
                //var email = from a in db.Users
                //             where a.Email == user.Email
                //             select a.Email;
                //var username = from a in db.Users
                //               where a.UserName == user.UserName
                //               select a.UserName;
               
                //if ( email.Count() == 0 && username.Count() == 0 )
                //{
                    db.Users.Add(user);
                    db.SaveChanges();
                    // return Redirect("Home/Index");
                    return RedirectToAction("Index", "Home");
            //    }
            //    else
            //    {
            //        if (email.Count() != 0)
            //            ModelState.AddModelError("Email", "Email address already exists. Try another email address.");
            //        if ( username.Count() != 0)
            //        {
            //            ModelState.AddModelError("UserName", "Username already exists. Try another username." );
            //        }
            //    }
            }

            return View(user);
        }

        public ActionResult Login()
        {
            ViewBag.login = true;
            return View();
        }

        [HttpPost]
        public ActionResult Login(Login login)
        {
            //ViewBag.login = false;
            if (ModelState.IsValid)
            {
                var user = db.Users.Where( a=>a.UserName == login.UserName && a.Password == login.Password);

                if ( user.Count() != 0 )
                {
                    User loginuser = db.Users.FirstOrDefault(a => a.UserName == login.UserName);
                    Session["login"] = "true";
                    
                    Session["username"] = login.UserName;
                    Session["userid"] = loginuser.Id; 
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ViewBag.login = false;
                }
            }
            else
            {
                ViewBag.login = true;
            }
            return View(login);
        }

        public ActionResult Logout()
        {
            Session["username"] = null;
            Session["userid"] = null; 
            Session["login"] = "false";
            return RedirectToAction("Index", "Home");
        }

        [HttpGet]
        public ActionResult UserProfile( string name )
        {
           
            User user = db.Users.FirstOrDefault( a => a.UserName == name);
            return View(user);
        }

        //
        // GET: /User/Edit/5

        public ActionResult Edit(int id = 0)
        {
            User user = db.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        //
        // POST: /User/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(User user)
        {
            if (ModelState.IsValid)
            {
                db.Entry(user).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(user);
        }

        //
        // GET: /User/Delete/5

        public ActionResult Delete(int id = 0)
        {
            User user = db.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        //
        // POST: /User/Delete/5

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            User user = db.Users.Find(id);
            db.Users.Remove(user);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}

推荐答案

,ErrorMessage = 请输入有效的电子邮件地址)]
public 虚拟 字符串电子邮件{获取; set ;}

[必需]
[DataType(DataType.Password)]
public virtual string 密码{获取; 设置;}

[必填]
[NotMapped]
[显示(Name = 确认密码)]
[比较( 密码,ErrorMessage = 密码和确认密码不匹配。)]
public string ConfirmPassword { get ; set ; }
[必需]
[显示(名称= 地址)]
public string 地址{ get ; set ; }

[必需]
[显示(名称= 国家)]
public string 国家{获得; set ; }
[必需]
[显示(名称= 城市)]
public string 城市{获取; set ; }
[必需]
[显示(名称= )]
public string 状态{获取; set ; }
[必需]
[显示(名称= Zip)]
public string Zip { get ; set ; }






// public virtual ICollection< RSVP> RSVP {get;组; }
}

public class 登录
{
[必需]
[显示(名称= 用户名)]
public string UserName { get ; set ; }

[必需]
[DataType(DataType.Password)]
public 字符串密码{获取; set ; }
}


}
", ErrorMessage = "Please enter a valid Email Address")] public virtual string Email { get; set; } [Required] [DataType(DataType.Password)] public virtual string Password { get; set; } [Required] [NotMapped] [Display(Name = "Confirm Password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } [Required] [Display(Name = "Address")] public string Address { get; set; } [Required] [Display(Name = "Country")] public string Country { get; set; } [Required] [Display(Name = "City")] public string City { get; set; } [Required] [Display(Name = "State")] public string State { get; set; } [Required] [Display(Name = "Zip")] public string Zip { get; set; } //public virtual ICollection<RSVP> RSVPs { get; set; } } public class Login { [Required] [Display(Name = "Username")] public string UserName { get; set; } [Required] [DataType(DataType.Password)] public string Password { get; set; } } }




// in my conroller
<pre lang="c#">using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BootstrapPager.Models;
using Microsoft.VisualBasic;

namespace BootstrapPager.Controllers
{
    public class UserController : Controller
    {
        private EmployeeDb db = new EmployeeDb();

        //
        // GET: /User/

        public ActionResult Index()
        {
            return View(db.Users.ToList());
        }

        //
        // GET: /User/Details/5

        public ActionResult Details(int id = 0)
        {
            User user = db.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        //
        // GET: /User/Create
        
        public ActionResult Create()
        {
            //if (Session["user"] != null)
            //{
                
            //    return View();
            //}
            //else { return Content("Please Login First"); }
            return View();
        }

        //
        // POST: /User/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(User user)
        {
            if (ModelState.IsValid)
            {
                //User users = (User)db.Users.Where((a => a.Email == user.Email) || );
                //var email = from a in db.Users
                //             where a.Email == user.Email
                //             select a.Email;
                //var username = from a in db.Users
                //               where a.UserName == user.UserName
                //               select a.UserName;
               
                //if ( email.Count() == 0 && username.Count() == 0 )
                //{
                    db.Users.Add(user);
                    db.SaveChanges();
                    // return Redirect("Home/Index");
                    return RedirectToAction("Index", "Home");
            //    }
            //    else
            //    {
            //        if (email.Count() != 0)
            //            ModelState.AddModelError("Email", "Email address already exists. Try another email address.");
            //        if ( username.Count() != 0)
            //        {
            //            ModelState.AddModelError("UserName", "Username already exists. Try another username." );
            //        }
            //    }
            }

            return View(user);
        }

        public ActionResult Login()
        {
            ViewBag.login = true;
            return View();
        }

        [HttpPost]
        public ActionResult Login(Login login)
        {
            //ViewBag.login = false;
            if (ModelState.IsValid)
            {
                var user = db.Users.Where( a=>a.UserName == login.UserName && a.Password == login.Password);

                if ( user.Count() != 0 )
                {
                    User loginuser = db.Users.FirstOrDefault(a => a.UserName == login.UserName);
                    Session["login"] = "true";
                    
                    Session["username"] = login.UserName;
                    Session["userid"] = loginuser.Id; 
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ViewBag.login = false;
                }
            }
            else
            {
                ViewBag.login = true;
            }
            return View(login);
        }

        public ActionResult Logout()
        {
            Session["username"] = null;
            Session["userid"] = null; 
            Session["login"] = "false";
            return RedirectToAction("Index", "Home");
        }

        [HttpGet]
        public ActionResult UserProfile( string name )
        {
           
            User user = db.Users.FirstOrDefault( a => a.UserName == name);
            return View(user);
        }

        //
        // GET: /User/Edit/5

        public ActionResult Edit(int id = 0)
        {
            User user = db.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        //
        // POST: /User/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(User user)
        {
            if (ModelState.IsValid)
            {
                db.Entry(user).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(user);
        }

        //
        // GET: /User/Delete/5

        public ActionResult Delete(int id = 0)
        {
            User user = db.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        //
        // POST: /User/Delete/5

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            User user = db.Users.Find(id);
            db.Users.Remove(user);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}


In my article Drag And Drop Role Management with Asp.Net, MVC & jQuery[^] you can see how I check the role the current user has to see if they have the authority to run the action.



During the initialisation of the system you can add the roles into the database by calling a method in the global.asax Application_Start;



Obviously you would do this on the first run just to set things up. Later on you can either comment this out or do some logic checking to see if the roles or user accounts already exist.

In my article Drag And Drop Role Management with Asp.Net, MVC & jQuery[^] you can see how I check the role the current user has to see if they have the authority to run the action.

During the initialisation of the system you can add the roles into the database by calling a method in the global.asax Application_Start;

Obviously you would do this on the first run just to set things up. Later on you can either comment this out or do some logic checking to see if the roles or user accounts already exist.
protected void Application_Start()
{

    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    //Initialise the Database
    //Database.SetInitializer(new DropCreateDatabaseAlways<TM470Project.DBContexts.DrillingDailyReportsDBContext>());
    //Database.SetInitializer(new DropCreateDatabaseAlways<TM470Project.DBContexts.KPIDailyDBContext>());


    //Initialise the user database Roles - Note:Set to true only during dev when cleaning up old roles being removed.
    InitialiseRoles(false);

    //Initialise the default SuperUser + Guest Account
    InitialiseDefaultUsers();

    //Use the new combined context for the intialiser
    Database.SetInitializer(new DropCreateDatabaseIfModelChanges<TM470Project.DBContexts.CombinedDBContext>());

}





then the two methods are



then the two methods are

private void InitialiseRoles(Boolean DeleteExistingRoles)
        {

            if (DeleteExistingRoles)
            {
                //Delete All Existing Roles
                //Get list of Roles
                String[] oldRoles = Roles.GetAllRoles();

                foreach (String role in oldRoles)
                {
                    //Get all the usernames with Role
                    String[] users = Roles.GetUsersInRole(role);

                    //Remove all the users from Role
                    foreach (String user in users)
                    {
                        Roles.RemoveUserFromRole(user, role);
                    }

                    //Delete the Role
                    Roles.DeleteRole(role);

                }
            }

            //Roles list to be used by application
            String[] NewRoles = new String[] {"KPI-Daily-View","KPI-Daily-Create", "KPI-Daily-Edit", "KPI-Daily-Delete", "KPI-Losses-View","KPI-Losses-Create","KPI-Losses-Edit","KPI-Losses-Delete", "Drilling-Report-View","Drilling-Report-Create","Drilling-Report-Edit","Drilling-Report-Delete", "Admin-User-View","Admin-User-Add","Admin-User-Edit","Admin-User-Delete","Admin-User-ChangePassword", "Admin-Assets-View","Admin-Assets-Create","Admin-Assets-Edit","Admin-Assets-Delete"};

            //Check if role exists and add if not
            foreach (String role in NewRoles)
            {
                if (!Roles.RoleExists(role))
                {
                    Roles.CreateRole(role);
                }
            }
        }





You can then add the default users onto the system by doing;



You can then add the default users onto the system by doing;

private void InitialiseDefaultUsers()
        {
            MembershipUser user = null;

            //Default SuperUser Account
           user = Membership.GetUser("SuperUser");
           if (user == null)
           {
               //Account does not exist
               Membership.CreateUser("SuperUser", "ThePassword","SuperUser@the-email.net");
           }

           //Check the SuperUser account has all roles
           String[] roles = Roles.GetAllRoles();
           foreach (String role in roles)
           {
               if (!(Roles.IsUserInRole("SuperUser", role)))
               {
                   Roles.AddUserToRole("SuperUser", role);
               }
           }

            //Default Guest Account
           user = Membership.GetUser("Guest");
           if (user==null)
           {
               //Account does not exist
               Membership.CreateUser("Guest", "guest-password", "guest@the-email.net");
           }

            //Add roles to Guest Account
            String[] guestRoles = new String[] {"KPI-Daily-View","KPI-Losses-View","Drilling-Report-View"};
            foreach (String role in guestRoles)
            {
                if (!(Roles.IsUserInRole("Guest", role)))
                {
                    Roles.AddUserToRole("Guest", role);
                }
            }

        }





Note: the code above is from my OU project that the drag and drop article was also based on, hence all those different roles for the different things the application was doing.



Note: the code above is from my OU project that the drag and drop article was also based on, hence all those different roles for the different things the application was doing.


这篇关于如何在其上添加角色和成员资格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆