播种数据和MVC4创建/管理角色 - 如何努力,能有呢? [英] Seeding data and creating/managing roles in MVC4 - how hard can it be?

查看:136
本文介绍了播种数据和MVC4创建/管理角色 - 如何努力,能有呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我快要发疯,所以我会尽力得到一些帮助更多的时间...
我使用Visual Studio的前preSS 2012的Web创建一个使用C#+ MVC4 +剃刀+ Entity Framework的ASP.NET + 4.5的互联网项目。
我需要做到以下几点:自动创建一个admin用户(谁将会被授权各地的网站),然后创建一些用户角色。
我读过有关SimpleMembership,角色,一切都在网上,但似乎没有给我一个简单的方法来使整个事情的工作。

I'm about to go insane, so I'll try getting some help one more time... I'm using Visual Studio Express 2012 for Web to create an internet project using C# + MVC4 + Razor + Entity Framework + ASP.NET 4.5. I need to do the following: automatically create an "admin" user (who will be authorized all over the site) and then create some user roles. I've read about SimpleMembership, roles and everything all over the web, but nothing seems to give me a straightforward method to make the whole thing work.

这是我迄今所做的:

1 - 创建一个DataContext类:

1- Created a DataContext class:

public class DataContext : DbContext
{
public DataContext()
: base("DefaultConnection")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
}

2 - 创建初始化类我认为会得到我所创建的管理员用户和管理员的角色:

2- Created an initializer class with what I assume would get me the admin user and Admins role created:

public class DataContextDbInitializer : DropCreateDatabaseAlways<DataContext>
{
protected override void Seed(DataContext context)
{
var roles = (Webmatrix.WebData.SimpleRoleProvider)System.Web.Security.Roles.Provider;
var membership = (Webmatrix.WebData.SimpleMembershipProvider)System.Web.Security.Membership.Provider;
if (!roles.RoleExists("Admins")) {
roles.CreateRole("Admins");
}
if (membership.GetUser("admin", false) == null) {
membership.CreateUserAndAccount("admin", "123456");
}
if (!roles.GetRolesForUser("admin").Contains("Admins")) {
roles.AddUsersToRoles(new[] { "admin" }, new[] { "Admins" });
} 
}
}

(我试过从DropCreateDatabaseIfModelChanges继承但这并不能帮助)。

(I've tried inheriting from DropCreateDatabaseIfModelChanges but that doesn't help).

3 - 新增两条线的方法App_Start在Global.asax中:

3- Added two lines to the App_Start method in Global.asax:

WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
Database.SetInitializer<DataContext>(new DataContextDbInitializer());

我也试过在我DataContextDbInitializer类种子的方法使用WebSecurity.InitializeDatabaseConnection,但没有奏效。

I also tried using WebSecurity.InitializeDatabaseConnection in the Seed method in my DataContextDbInitializer class, but didn't work.

4 - 移除了的AccountController的[InitializeSimpleMembership]注释,这样我就可以从应用程序生命周期(以App_Start使用WebSecurity.InitializeDatabaseConnection的开始初始化,因为我已经解释了号3)。我试着在HomeController的Index方法的顶部添加[InitializeSimpleMembership]和App_Start去除WebSecurity.InitializeDatabaseConnection,但这并没有帮助。

4- Removed the [InitializeSimpleMembership] annotation from the AccountController, so I can initialize it from the very beginning of the application life cycle (using WebSecurity.InitializeDatabaseConnection in App_Start, as I've explained in number 3). I tried adding [InitializeSimpleMembership] on top of the Index method in the HomeController and removing WebSecurity.InitializeDatabaseConnection from App_Start, but that doesn't help either.

5 - 在web.config中我的身份验证方法,形式(默认)和也离开了默认的连接字符串:

5- In Web.config I have authentication method as Forms (default) and also left the default connection string:

<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-TPFinal-20130121210447;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-TPFinal-20130121210447.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>

和添加了这个对System.Web标签内:

And added this inside the system.web tag:

<roleManager enabled="true" cacheRolesInCookie="true" />

6 - 然后,以测试是否一切正常,我用的是[授权(角色=管理员)在HomeController的关于在()方法的顶部注释。如果按预期事情,这应该强迫我登录为管理员/ 123456,以便能够看到关于页面上,通过控制的HomeController /关于

6- Then, to test if everything works, I use the [Authorize(Roles = "Admins")] annotation on top of the About() method in the HomeController. If things were working as expected, this should force me to log in as admin/123456 in order to be able to see the "About" page, controlled by HomeController/About.

7 - 我没有加入EF迁移或其他任何东西。所有其他的东西是被默认设置为VS2012自动创建它。
所以,我跑我的应用程序,然后点击关于链接,和我获得与登录表单psented $ P $(这意味着,[授权(角色=管理员)注释是做什么它是预料之中的事)。我试图登录的管理员/ 123456但日志中的页面重新加载一遍又一遍,每次我点击登录按钮的时间。

7- I haven't added EF migrations or anything else. All the other stuff is by default as VS2012 automatically created it. So I run my application and click on the "About" link, and I get presented with the login form (that means that the [Authorize(Roles = "Admins")] annotation is doing what it's expected to do). I attempt to log in as admin/123456 but the log in page is reloaded over and over, every time I click on the log in button.

有几件事情我已经注意到:

A few things I have noticed:

- 如果我在种方法添加一个断点,好像它没有得到所谓的。

-if I add a breakpoint in the Seed method, it seems it's not getting called.

- 当我用DropCreateDatabaseAlways并再次运行该应用程序,我能够以Admin身份登录/ 123456,这让我再次觉得甚至没有使用我的整个DataContextDbInitializer类,因为我承担DB应创建从头开始,这将删除admin用户。

-when I use DropCreateDatabaseAlways and run the application again, I'm able to log in as admin/123456, which makes me think again that my whole DataContextDbInitializer class is not even being used, since I assume the DB should be created from scratch, which would delete the admin user.

我不知道看还有什么,还有什么尝试...我是新来asp.net(需要我说吗?),只是去坚果。
谢谢!

I don't know what else to read, what else to try... I'm new to asp.net (needed I say that?) and just going nuts. Thanks!!

推荐答案

在MVC4一个默认的Internet应用程序已验证内置。 位于一个过滤器的目录名为 InitializeSimpleMembershipAttribute的类。顾名思义这个类初始化简单的会员数据库。如果你看一下构造函数,你会看到以下行:

In MVC4 a default Internet Application has Authentication built-in. A class called InitializeSimpleMembershipAttribute is located in a Filters directory. As the name suggests this class Initializes the Simple Membership Database. If you look at the constructor you'll see the following line:

 WebSecurity.InitializeDatabaseConnection("UserContext", "UserProfile", "UserId", "UserName", autoCreateTables: true);

下面这行你可以插入以下code创建一个默认的用户:

Below this line you can insert the following code to create a default user:

// Create admin user.
                    if (!WebSecurity.UserExists("admin"))
                    {
                        WebSecurity.CreateUserAndAccount("admin", "12345678!");
                    }

只是另一种方式来做事。

Just another way to do things.

这篇关于播种数据和MVC4创建/管理角色 - 如何努力,能有呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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