究竟如何使用角色在Asp.NET MVC 4? [英] How exactly do I use Roles in Asp.NET MVC 4?

查看:322
本文介绍了究竟如何使用角色在Asp.NET MVC 4?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读吨的文章和论坛,但我仍然无法弄清楚...
我建立使用Visual Studio防爆preSS 2012年网络的互联网应用,以MVC4 +剃刀+实体框架codeFirst。

I've been reading tons of articles and forums but I still can't figure it out... I'm building an internet application using Visual Studio Express 2012 for Web, with MVC4+Razor+Entity Framework CodeFirst.

据我了解,管理用户和角色MVC4与SimpleMembership更直接比它在previous版本,并应该是相当简单的。

As far as I understand, managing users and roles in MVC4 with SimpleMembership is more straightforward than it was in previous versions and should be fairly simple.

在我的应用程序,我需要授权用户只(例如,只有管理员可以访问某些网页)的某些群体。据我所知,是通过传递一个参数到[授权]注释提出:[授权(角色=管理员)]
但我怎么创造这些角色?如何将用户添加到他们?

In my application, I need to authorize only certain groups of users (e.g., only admins can access certain pages). I understand that's made by passing a parameter to the [Authorize] annotation: [Authorize(Roles="Admins")] But how do I create those roles and how do I add users to them?

在为需要身份验证,我添加注释的 [授权] (不带参数)上的控制器方法的顶部,它的工作没有作出任何额外的配置或添加任何东西。此外,当我看看这是自动创建的数据库,我看到一个表名为webpages_UsersInRoles,与列用户ID和角色ID。所有这一切都让我觉得这是一个pretty简单的任务,因为一切似乎设置并随时可以使用,但我只是无法弄清楚如何;)

In order to require authentication I added the annotation [Authorize] (with no parameters) on top of a controller method and it worked without having made any extra configurations or adding anything else. Also, when I take a look at the database that was automatically created, I see a table named webpages_UsersInRoles, with columns UserId and RoleId. All of this makes me think this has to be a pretty simple task since all seems set up and ready to be used, but I just can't figure out how ;)

我到目前为止已经试过(和它没有工作)是这样的:
我有一个DataContextDbInitializer级,从DropCreateDatabaseIfModelChanges继承。种子法重写这个类里面,我说这(我不得不进口System.Web.Security):

What I've tried so far (and it didn't work) was this: I have a "DataContextDbInitializer" class that inherits from DropCreateDatabaseIfModelChanges. The Seed method is overriden inside that class, and I added this (I had to import System.Web.Security):

Membership.CreateUser("user1", "123456");
Roles.CreateRole("Admins");
Roles.AddUserToRole("user1", "Admins");

我也是在Web.config文件的标签插入此标记:

I also inserted this tag in the tag of the Web.config file:

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

要尝试一下,我添加[授权(角色=管理员)上的操作方法的顶部控制器,然后登录为管理员,并试图访问该方法,但没有运气:(

To try it out I added [Authorize(Roles="Admins")] on top of an action method in a controller, and then logged in as "admin" and tried to access that method, but no luck :(

我不知道我错过了些什么?
我会真的很高兴,如果有人能指导我通过这个,因为它让我疯狂:P

I don't know what else I'm missing... I'd be really happy if anyone could guide me through this, since it's driving me insane :P

谢谢!

推荐答案

我的猜测是,你的种子的方法是没有得到调用。验证这一点得到通过把一个破发点中的方法,并在调试器中运行它叫。除非你做了一些其他更改您的应用程序没有使用EF迁移。默认情况下,数据库初始化为 InitializeSimpleMembershipAttribute 。你会看到,这个属性添加到账户控制器为显示在下面的code。

My guess is that your Seed method is not getting called. Verify this is getting called by putting a break point in the method and running it in the debugger. Unless you made some other changes to your application the EF migration is not being used. By default the database is initialized with the InitializeSimpleMembershipAttribute. You will see that this attribute is added to the Account Controller as shown in the following code.

[Authorize]
[InitializeSimpleMembership]
public class AccountController : Controller
{
  ....
}

此方式,仅调用时在的AccountController 进行访问。你会发现在过滤器\\ InitializeSimpleMembershipAttribute.cs的定义。下面是这个类,可能是线索,为什么它不能被称为一个code片段。

This way it is only invoked when the AccountController is accessed. You will find the definition in Filters\InitializeSimpleMembershipAttribute.cs. Here is a code snippet from this class that may be clue to why it not being called.

// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();

在很多code的 InitializeSimpleMembershipAttribute 的到位,以处理这种情况窗体身份验证不用于MVC应用程序的情况。如果你将永远是使用窗体身份验证即可消除此code和自己初始化数据库。只是删除从的AccountController这个属性,并把自己的初始化code在Global.asax 的Application_Start 方式。你会喜欢这个东西添加到的Application_Start 方式

A lot of the code in InitializeSimpleMembershipAttribute is put in place to handle the scenario where Forms Authentication is not used for the MVC application. If you will always be using Forms Authentication you can eliminate this code and initialize the database yourself. Just remove this attribute from the AccountController and put your own initialization code in the Global.asax Application_Start method. You would add something like this to the Application_Start method

Database.SetInitializer<UsersContext>(new MyDBInitializer());

种子的方法是这样的

The Seed method look like this

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

var roles = (SimpleRoleProvider)Roles.Provider;
var membership = (SimpleMembershipProvider)Membership.Provider;

if (!roles.RoleExists("Admin"))
{
     roles.CreateRole("Admin");
}
if (membership.GetUser("user1", false) == null)
{
     membership.CreateUserAndAccount("user1", "123456");
}
if (!roles.GetRolesForUser("user1").Contains("Admin"))
{
    roles.AddUsersToRoles(new[] { "user1" }, new[] { "Admin" });
} 

请注意,你需要在种子方法来初始化网络矩阵安全数据库调用的 WebSecurity.InitializeDatabaseConnection 方式。

Note that you need to initialize the web matrix security database in your Seed method by calling the WebSecurity.InitializeDatabaseConnection method.

您可以找到在此博客帖子,其中包括完整的源$ C ​​$ C实例项目。

You can find more detailed information on seeding SimpleMembership in this blog post, which includes the complete source code for the example project.

这篇关于究竟如何使用角色在Asp.NET MVC 4?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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