WebSecurity的簡單用法

來源:互聯網
上載者:User

標籤:

添加一個帶有使用表單身分識別驗證的帳戶控制器的預設 ASP.NET MVC 4 項目,如果用codefirst會自動產生幾張表。

<connectionStrings>    <add name="DefaultConnection" connectionString="Data Source=.;Initial Catalog=WebSecurity;Persist Security Info=True;User ID=sa;Password=1q2w3e4r" providerName="System.Data.SqlClient" />  </connectionStrings>
 public class EntityContext : DbContext    {        public EntityContext()            : base("DefaultConnection")        {                   }        public DbSet<UserProfile> UserProfiles { get; set; }        //protected override void OnModelCreating(DbModelBuilder modelBuilder)        //{        //    base.OnModelCreating(modelBuilder);        //    modelBuilder.Entity<UserProfile>().ToTable("");                 //}    }

資料庫產生5張表:

UserProfile、webpages_Membership、webpages_OAuthMembership、webpages_Roles、webpages_UsersInRoles

註冊使用者

        [HttpPost]        [AllowAnonymous]        [ValidateAntiForgeryToken]        public ActionResult Register(RegisterModel model)        {            if (ModelState.IsValid)            {                // 嘗試註冊使用者                try                {                    //建立使用者                    WebSecurity.CreateUserAndAccount(model.UserName, model.Password);                    //建立角色                    if (!Roles.RoleExists("superAdmin"))                    {Roles.CreateRole("superAdmin"); }                    if (!Roles.RoleExists("admin"))                    { Roles.CreateRole("admin"); }                    if (!Roles.RoleExists("user"))                    { Roles.CreateRole("user"); }                    //將使用者添加到角色                    Roles.AddUserToRole(model.UserName, "user");                    var id = WebSecurity.GetUserId(model.UserName);                                       WebSecurity.Login(model.UserName, model.Password);                    return RedirectToAction("Index", "Home");                }                catch (MembershipCreateUserException e)                {                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));                }            }            // 如果我們進行到這一步時某個地方出錯,則重新顯示表單            return View(model);        }

這樣除了第三張表都有了資料,OAuthMembership表有三個欄位Provider、ProviderUserId、UserId,應該和驗證方式的配置有關。

 

WebSecurity的簡單用法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.