Asp.net Mvc4 the default permissions (up) with

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

Preface

The first rookie to repeat the Sql problem has not received a satisfactory answer. If any brother related data interpretation, can share with me, then thank you so much.

After each published a blog I will point out the issues left over from the past in the foreword, until the settlement date.

The main aim of this thesis is to discuss the details of Asp.net Mvc4 generated by default permissions.

Introduction

Create a MVC4 Internet project default permissions in VS2012, as shown below.

The operating point when the project is built, landing in the browser. Then observe the project, at the moment generated database, as follows.

This paper is aimed at the analysis of the existing authority complete such a template project, hope that we can learn something from it, if you have any questions, please indicate. PS: welcome to discuss progress.

Funny Attribute

There are three ActionFilter above, do not know ActionFilter children please click here.

AuthorizeAttribute: represents a characteristic, the characteristic is used to limit the caller of the operation method of access.

AllowAnonymousAttribute: Represents a characteristic, the characteristic is used to mark to the controller and operation to skip the AuthorizeAttribute authorization in the period.

InitializeSimpleMembershipAttribute: This feature is to initialize the database relationships, will later.

Authorize

This Attribute is used to limit the user roles, we should all know, here not much said.

AllowAnonymous

The Attribute seems to be MVC4 added. You look at the above interpretation should also understand the. Is actually the Microsoft team plus the judgment of AllowAnonymous implementation in Authorize, if the Attribute method is not restricted.

The truth here (reversed), this is the OnAuthorization method of the Authorize, interested in children's shoes can have a look 12.

 1          public virtual void OnAuthorization(AuthorizationContext filterContext)
 2         {
 3             if (filterContext == null)
 4             {
 5                 throw new ArgumentNullException("filterContext");
 6             }
 7             if (OutputCacheAttribute.IsChildActionCacheActive(filterContext))
 8             {
 9                 throw new InvalidOperationException(MvcResources.AuthorizeAttribute_CannotUseWithinChildActionCache);
10             }
11             bool inherit = true;
12             if (!filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit) && !filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
13             {
14                 if (this.AuthorizeCore(filterContext.HttpContext))
15                 {
16                     HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;
17                     cache.SetProxyMaxAge(new TimeSpan(0L));
18                     cache.AddValidationCallback(new HttpCacheValidateHandler(this.CacheValidateHandler), null);
19                 }
20                 else
21                 {
22                     this.HandleUnauthorizedRequest(filterContext);
23                 }
24             }
25         }

Here's to the main about the default permissions on the key Attribute.

InitializeSimpleMembership

We'll come to realize it

 1    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
 2    public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
 3     {
 4         private static SimpleMembershipInitializer _initializer;
 5         private static object _initializerLock = new object();
 6         private static bool _isInitialized;
 7 
 8         public override void OnActionExecuting(ActionExecutingContext filterContext)
 9         {
10             // Ensure ASP.NET Simple Membership is initialized only once per app start
11             LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
12         }
13 
14         private class SimpleMembershipInitializer
15         {
16             public SimpleMembershipInitializer()
17             {
18                 Database.SetInitializer<UsersContext>(null);
19 
20                 try
21                 {
22                     using (var context = new UsersContext())
23                     {
24                         if (!context.Database.Exists())
25                         {
26                             // Create the SimpleMembership database without Entity Framework migration schema
27                             ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
28                         }
29                     }                  
30                     WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
31                 }
32                 catch (Exception ex)
33                 {
34                     throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
35                 }
36             }
37         }
38     }

In this Atrribute to create the database we first met.

Now let us have a look how. The create database or Code First and previously used a bit out.

4-12 is mainly defined several variables and override the OnActionExcuting, the Asp.net members to ensure initialized only once. We can expect, the inevitable in LazyInitializer.EnsureInitialized function inside the SimpleMembershipInitializer.

Initializes only a means that does not call the constructor for SimpleMembershipInitializer two. In fact, look at the code we should generally be able to guess, this constructor mainly do is create the database functions, of course the best implemented only once.

22-29 is the main method to create UsersContext database, the related code is as follows

    public class UsersContext : DbContext
    {
        public UsersContext()
            : base("DefaultConnection")
        {
        }

        public DbSet<UserProfile> UserProfiles { get; set; }
    }

    [Table("UserProfile")]
    public class UserProfile
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int UserId { get; set; }
        public string UserName { get; set; }
    }

From the above we can understand the UsersContext successor to the DbContext, and with DefaultConnection string for the connection string, a piece of table UserProfile.

Then we will have doubt, that a few at the beginning of the article introduces the marked in table is generated. Don't worry, we continue to look down

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

This phrase can guess. Initialize the database connection using the connection string Default, UserProfile, UserId field, UserName automatically creates a table,.

But before we have used UserContext (CreateDatabase) to create a database and table. Don't try to create a!!? That'll be fine. Let us have a look the interpretation of MSDN.!

InitializeDatabaseConnection()

To initialize the membership system by connecting to the database containing the user information.

Notes

In this method is called when the application starts (in the _AppStart.cshtml or _AppStart.vbhtml file), to initialize simple membership system. Membership database to verify this method is present. It is also open to the user connection configuration file table, and the establishment of a database relation between the membership data and user profile data.

If you want to use contains the user profile information (name, email address, etc.) of the database table, you should specify the membership system for connection to the information of the connection string and table name. If you do not want to use an existing user configuration file table, you can specify the InitializeDatabaseConnection () method to automatically create a user profile table. (user database configuration file table must already exist. )

Here is an explanation of the five parameter method:

connectionStringName

The name of the connection string contains a user information database. If you are using SQL Server Compact, this name can be a non.Sdf file name extension database file (.Sdf file) name.

userTableName

Name of the database table that contains the user profile information.

userIdColumn

The name of the database column contains the user ID. This column must be in the form of type integer (int).

userNameColumn

Contains the name of the database user name column. This column is used to match a user profile data and membership account data.

autoCreateTables

If true, indicates that should create user profile table and membership list (if they do not exist). If false, indicates that should not automatically create the tables. Although you can automatically create the membership list, but the database itself must already exist.

I understand

This method will be on the existing database analysis, if not ahead to create the database, calling this method will error.

If you have created an empty database and there is no corresponding userTableName table, set autoCreateTables to true, will automatically create the parameter name tables, fields and userIdColumn and userNameColumn corresponding to the one one, and create four membership list the rest.

If autoCreateTables is set to false, will not automatically create any table.

Set autoCreateTables to true, if you have to use UserContext to create the user table, the table name and field name UserId, UserName as a parameter is assigned to the InitializeDatabaseConnection () method as a parameter, the name of the table is not consistent, the database will create a User table, and the method of parameter names to the use of the webSecurity method. The field names are not consistent, use the webSecurity method of the error when.

At this point, we know roughly at first to see that several data table is generated. The webSecurity.InitializeDatabaseConnection method, is implemented automatically.

Summary

Was going to give this part of the content is generated by default permissions as far as possible in an inside out, but the process of writing a blog that need to write a little more.

But I was the rookie, content slightly more, more and more feels a bit messy, so going to divide two parts to write.

Ha-ha. At present there is no strength to write novels, that requires thinking clear enough, I still need to exercise.!

The next I'm going to write about WebSecurity, SimpleMemberShip, RoleProvider, and their use in situations where Asp.net Mvc4 default permissions (down), with hope that interested children continue to pay attention to!

Finally, if we have any problems, please also indicate. If you can help, please help recommend give me more power!



Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by April at November 13, 2013 - 7:42 AM