我正在使用Asp.net MVC开发SPA。项目适用于localhost,但我在托管时遇到了问题。
有一个控制器可以与MembershipProvider
一起使用很少的方法。
[InitializeSimpleMembership]
public class AccountController : ApiController
{
public object Get()
{
...
}
...
}
关键时刻 - 是属性InitializeSimpleMembership
。它的声明:
[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(System.Web.Http.Controllers.HttpActionContext actionContext)
{
// 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(new ITAInitializer());
using (var context = new ITAContext())
{
if (!context.Database.Exists())
{
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
WebSecurity.InitializeDatabaseConnection("ITAContext", "Users", "ID", "Login", autoCreateTables: true);
if (!Roles.RoleExists(UserRights.Admin.ToString()))
Roles.CreateRole(UserRights.Admin.ToString());
if (!Roles.RoleExists(UserRights.Moderator.ToString()))
Roles.CreateRole(UserRights.Moderator.ToString());
if (!Roles.RoleExists(UserRights.User.ToString()))
Roles.CreateRole(UserRights.User.ToString());
}
}
}
当我在控制器中调用任何方法时,我收到错误:
数据库中已有一个名为“Users”的对象。
如果我正在删除表Users
,那么首先请求正常运行并创建表。在接下来的电话中我再次收到错误。为什么它试图创建表而不使用现有的?
答案 0 :(得分:1)
在某个类中添加方法WebSecurity.InitializeDatabaseConnection
:
public static class AuthConfig
{
public static void RegisterAuth()
{
WebSecurity.InitializeDatabaseConnection("ITAContext", "Users", "ID", "Login", autoCreateTables: true);
if (!Roles.RoleExists(UserRights.Admin.ToString()))
Roles.CreateRole(UserRights.Admin.ToString());
if (!Roles.RoleExists(UserRights.Moderator.ToString()))
Roles.CreateRole(UserRights.Moderator.ToString());
if (!Roles.RoleExists(UserRights.User.ToString()))
Roles.CreateRole(UserRights.User.ToString());
}
}
调用此方法:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AuthConfig.RegisterAuth();
}
}
答案 1 :(得分:1)
问题在于db用户的权限。添加VIEW DEFINITION
和ALTER
后,我的代码运行正常。