C# 在调用“WebSecurity”类的任何其他方法之前,您必须调用“WebSecurity.InitializeDatabaseConnection”方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17839032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
You must call the "WebSecurity.InitializeDatabaseConnection" method before you call any other method of the "WebSecurity" class
提问by DarthVader
Everytime I restart Debugging with Visual Studio I get this freaking error:
每次我用 Visual Studio 重新启动调试时,我都会收到这个可怕的错误:
You must call the "WebSecurity.InitializeDatabaseConnection" method before you call any other method of the "WebSecurity" class. This call should be placed in an _AppStart.cshtml file in the root of your site.
在调用“WebSecurity”类的任何其他方法之前,您必须调用“WebSecurity.InitializeDatabaseConnection”方法。此调用应放置在站点根目录中的 _AppStart.cshtml 文件中。
But that is everytime, and when i deploy the app to prod. I get this error here and then, randomly.
但那是每次,当我将应用程序部署到 prod 时。我在这里然后随机收到此错误。
I do put the proper tag :
我确实放了正确的标签:
[Authorize(Roles = "admin")]
[InitializeSimpleMembership]
public class IndexController : Controller
to controller and here is the filter the way it is. It just doesnt wanna work.
到控制器,这里是过滤器的样子。它只是不想工作。
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Threading;
using System.Web.Mvc;
using MeetingTaskManagement.Models;
using WebMatrix.WebData;
namespace MeetingTaskManagement.Filters
{
[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 UsersContext())
{
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);
}
}
}
}
}
can someone help me sort this out?
有人可以帮我解决这个问题吗?
采纳答案by Bastaspast
Remove the SimpleMemberShip attribute from your controllers and trash it. Add the following to your global.asax.
从控制器中删除 SimpleMemberShip 属性并将其丢弃。将以下内容添加到您的 global.asax。
private static SimpleMembershipInitializer _initializer;
private static object _initializerLock = new object();
private static bool _isInitialized;
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
}
public class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
using (var context = new UsersContext())
context.UserProfiles.Find(1);
if (!WebSecurity.Initialized)
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
}
回答by DarthVader
I was being a smartass by using a single context both for Membership provider and for my domain models. It turns out that was the problem; you can't use Membership provider and domain classes in a single context.
通过为成员资格提供程序和我的域模型使用单一上下文,我变得很聪明。事实证明这就是问题所在。您不能在单个上下文中使用成员身份提供程序和域类。
You need to have two contexts.
你需要有两个上下文。
回答by Bolt Thunder
To simplify your Global.asax, you can put the code for initialization into class AuthConfig
like this:
为了简化你的 Global.asax,你可以把初始化代码变成class AuthConfig
这样:
public static class AuthConfig
{
private static SimpleMembershipInitializer _initializer;
private static object _initializerLock = new object();
private static bool _isInitialized;
public static void RegisterAuth()
{
// Ensure ASP.NET Simple Membership is initialized only once per app start
LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
// To let users of this site log in using their accounts from other sites such as Microsoft, Facebook, and Twitter,
// you must update this site. For more information visit http://go.microsoft.com/fwlink/?LinkID=252166
//OAuthWebSecurity.RegisterMicrosoftClient(
// clientId: "",
// clientSecret: "");
//OAuthWebSecurity.RegisterTwitterClient(
// consumerKey: "",
// consumerSecret: "");
//OAuthWebSecurity.RegisterFacebookClient(
// appId: "",
// appSecret: "");
//OAuthWebSecurity.RegisterGoogleClient();
}
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
Database.SetInitializer<UsersContext>(null);
try
{
using (var context = new UsersContext())
{
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);
}
}
}
}
回答by lienysd
I just switch the [InitializeSimpleMembership] to HomeController, and erase it from AccountController. Because the initializations are made in a lazy way.. I just want to rush it.. and it worked!!!
我只是将 [InitializeSimpleMembership] 切换到 HomeController,然后从 AccountController 中删除它。因为初始化是以一种懒惰的方式进行的..我只想着急..它奏效了!!!
回答by raju1208
The requirement is only to call the WebSecurity Database Connection, you can do the following which is working:
要求只是调用 WebSecurity 数据库连接,您可以执行以下操作:
var WebSecDBContx = new UsersContext();
var CreatedByUser = WebSecDBContx.UserProfiles.Find(UserID);
string CreatedByUserName = CreatedByUser.UserName;
回答by Daniel Madriz
Why not just create the _AppStart.cshtml in the project root and place the initialization code in there as the error message states.
为什么不直接在项目根目录中创建 _AppStart.cshtml 并将初始化代码放在那里作为错误消息状态。
@{WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection("DefaultConnection", "TableName", "ColumnId", "ColumnName", autoCreateTables: false);}