[ChildActionOnly] [AllowAnonymous] public ActionResult NavBar() { NavBarviewmodel viewmodel = new NavBarviewmodel(); viewmodel.LinkItems = new List<NavBarLinkItem>(); if (Request.IsAuthenticated) { SimpleRoleProvider roleProvider = new SimpleRoleProvider(); if (roleProvider.IsUserInRole(User.Identity.Name,"User")) { viewmodel.LinkItems.Add(new NavBarLinkItem() { Title = "Create Project",Action = "Create",Controller = "Project" }); } } viewmodel.LinkItems.Add(new NavBarLinkItem() { Title="Help",Action="Index",Controller="Help" }); return PartialView("_NavBar",viewmodel); }
原来是这样,代码崩溃在“if(roleProvider.IsUserInRole(User.Identity.Name,”User“))”与主题错误消息。所以我进入InitialzeSimpleMembershipAttribute.cs文件,并将这行复制/粘贴到我的函数的顶部:
WebSecurity.InitializeDatabaseConnection("DefaultConnection","UserProfile","UserId","UserName",autoCreateTables: true);
…并收到WebSecurity.InitializeDatabaseConnection只应调用一次的错误消息。这是有道理的,因为在控件定义的顶部有一个应该已经调用了这个函数的属性(看起来好像这样)。所以要安全,我更改以上调用:
if (!WebSecurity.Initialized) { WebSecurity.InitializeDatabaseConnection("DefaultConnection",autoCreateTables: true); }
…并收回原来的错误消息,WebSecurity.InitializeDatabaseConnection应该在blah blah blah之前调用。对这种疯狂的任何洞察将不胜感激
解决方法
http://odetocode.com/blogs/scott/archive/2012/09/24/perils-of-the-mvc4-accountcontroller.aspx
这就是你要做的所有事情:
>从AccountController顶部删除[InitializeSimpleMembership]
>将来自/Filters/InitializeSimpleMembershipAttribute.cs(第39行)的WebSecurity.InitializeDatabaseConnection(…)调用复制到/AppStart/AuthConfig.cs
>随意从你的项目中删除InitializeSimpleMembershipAttribute.cs
您不必将InitializeDatabaseConnection()调用添加到AuthConfig.RegisterAuth(),但它似乎是逻辑的位置,并保持您的Global.asax更清洁。
你本来在做的是从原始属性中提取初始化调用,并在Application_Start上显式调用它。属性中的其他内容只是条件检查,以防您不使用(或不需要)SimpleMembership。