I'm trying to get SimpleMembership working for my ASP.Net MVC app. All of my controllers that need Authorization extend a base class called SecureController:
[Authorize]
[InitializeSimpleMembership]
[HandleException]
public class SecureController : Controller
{
protected UserProfile CurrentUser;
protected override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
var currentuserid = WebSecurity.CurrentUserId;
var context = new UsersContext();
CurrentUser = context.UserProfiles.SingleOrDefault(u => u.AuthenticationId == currentuserid);
if (CurrentUser != null)
{
ViewBag.UserName = CurrentUser.Name;
ViewBag.UserId = CurrentUser.Id;
}
}
}
I'm getting "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." error message when trying to call WebSecurity.CurrentUserId. I've put breakpoints in InitializeSimpleMembershipAttribute's OnActionExecuting but the breakpoints never hit. It seems like InitializeSimpleMembership is getting ignored.
I've added a call to InitializeSimpleMembershipAttribute in FilterConfig as well. FilterConfig.RegisterGlobalFilters gets called from Global.asax and this didnt help either.
Any ideas?
I place the call directly in Application_Start()
in Global.asax.cx
protected void Application_Start()
{
WebSecurity.InitializeDatabaseConnection("MembershipContext",
"WebUsers", "Id", "UserName", autoCreateTables: true);
// Other stuff from the template like AreaRegistration.RegisterAllAreas()
// etc.
}
That works fine.
The examples you find online tend to put that call in the constructor of SimpleMembershipInitializer()
. That did not work for me in the context of my overall application (though I can't recall exactly what the issue was).