与数据库.NET MVC简单成员身份验证 [英] .net MVC Simple Membership Authentication with Database
问题描述
使用code首先实体框架使用.NET MVC 4我创建了一个新的Web应用程序和填充对象的数据库,如下图所示。
Using Code First Entity Framework with .NET MVC 4 I have created a new Web Application and populated the database with object as shown below.
public class GratifyGamingContext : DbContext
{
public DbSet<Game> Games { get; set; }
public DbSet<Genre> Genres { get; set; }
public DbSet<UserProfile> UserRepository { get; set; }
}
我想用我的UserRepository表,而不是从AccountModel.cs内置的的UserContext类为我的用户帐户访问,因为我不能让与我现有的DbContext的工作。
I want to use my UserRepository table instead of the inbuilt UserContext class from AccountModel.cs for my user account access since I can't get that the work with my existing dbContext.
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; }
}
我的程序构建从InitializeSimpleMembershipAttribute.cs一个SimpleMembershipInitializer对象时总是崩溃。我已经注释掉code,我觉得应该是无关的。
My program always crashes when constructing a SimpleMembershipInitializer object from InitializeSimpleMembershipAttribute.cs. I have commented out the code I feel should be irrelevant.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
{
private static SimpleMembershipInitializer _initializer;
private static object _initializerLock = new object();
private static bool _isInitialized;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Ensure ASP.NET Simple Membership is initialized only once per app start
LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
}
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
//Database.SetInitializer<UsersContext>(null);
try
{
using (var context = new GratifyGamingContext())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
catch (Exception ex)
{
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);
}
}
}
}
我的ConnectionString如下:
My ConnectionString is as follows:
<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=aspnet-GratifyGaming-20120917185558;AttachDbFilename=|DataDirectory|\Games.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
调用任何的AccountController页面WebSecurity.InitializeDatabaseConnect时,我得到了以下错误:
I get the following error when calling the WebSecurity.InitializeDatabaseConnect from any AccountController page:
[SQLEXCEPTION(0x80131904):文件目录查找
C:\\用户\\虚幻\\文档\\ Visual Studio中
2010 \\项目\\ GratifyGaming \\ GratifyGaming.WebUI \\ App_Data文件\\ Games.mdf
与操作系统错误2失败(未能检索文本
这个错误。原因:15105)。无法附加文件
C:\\用户\\虚幻\\文档\\ Visual Studio中
2010 \\项目\\ GratifyGaming \\ GratifyGaming.WebUI \\ App_Data文件\\ Games.mdf'作为
数据库'ASPNET-GratifyGaming-20120917185558。]
[SqlException (0x80131904): Directory lookup for the file "C:\Users\Unreal\Documents\Visual Studio 2010\Projects\GratifyGaming\GratifyGaming.WebUI\App_Data\Games.mdf" failed with the operating system error 2(failed to retrieve text for this error. Reason: 15105). Cannot attach the file 'C:\Users\Unreal\Documents\Visual Studio 2010\Projects\GratifyGaming\GratifyGaming.WebUI\App_Data\Games.mdf' as database 'aspnet-GratifyGaming-20120917185558'.]
[TargetInvocationException:异常已被抛出的目标
调用] System.RuntimeTypeHandle.CreateInstance(RuntimeType
类型,布尔publicOnly,布尔NOCHECK,布尔和放大器; canBeCached,
RuntimeMethodHandleInternal&安培;构造函数,布尔和放大器; bNeedSecurityCheck)+ 0
[TargetInvocationException: Exception has been thrown by the target of an invocation.] System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
我的应用程序以其他方式连接到数据库,如果我没有去任何的AccountController驱动页面。
我该如何配置此应用程序使用我的UserRepository表,而不是UsersContext的用户会员资格?
My application is otherwise connected to the database if I do not go to any AccountController driven page. How can I configure this application to use my UserRepository table instead of the UsersContext for user membership?
推荐答案
从DefaultConnectionString web.config中删除AttachDbFileName
Remove the AttachDbFileName from the DefaultConnectionString in web.config
<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=aspnet-GratifyGaming-20120917185558;Integrated Security=True" providerName="System.Data.SqlClient" />
在打电话的Global.asax.cs中的方法WebSecurity.InitialiseDatabase
Call the WebSecurity.InitialiseDatabase method in Global.asax.cs
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
Database.SetInitializer<GratifyGamingContext>(new DatabaseInitializer());
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
WebSecurity.InitializeDatabaseConnection(
connectionStringName: "DefaultConnection",
userTableName: "UserProfile",
userIdColumn: "UserID",
userNameColumn: "UserName",
autoCreateTables: true);
}
}
注释掉[InitializeSimpleMembership]在AccountController.cs
Comment out [InitializeSimpleMembership] in AccountController.cs
[Authorize]
//[InitializeSimpleMembership]
public class AccountController : Controller
这篇关于与数据库.NET MVC简单成员身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!