Reputation: 2521
I've read through a number of SO questions on this topic, but all seem to be dealing with where you should put this call.
My problem is different: I have already done the WebSecurity.InitializeDatabaseConnection()
call, and have set breakpoints so I know it's been executed. But I still get the invalid operation exception
saying I have to call it.
Unlike most of the other questions which are encoutering it in an MVC controller action, I'm encountering it an HttpModule
I have written to accomplish Authentication for a REST WebAPI controller. The Init call contains the WebSecurity.InitializeDatabaseConnection
call. The OnAuthenticationRequest
method then extracts username and password information from the request's Authorization header, and calls the ValidateUser
method of the SimpleMembershipProvider
. This is where I get the exception
You must call the
WebSecurity.InitializeDatabaseConnection
method before you call any other method of theWebSecurity
class.
So
a) why am I getting this exception when I have already fulfilled the conditions not to get it.
b) what can be done about it?
Upvotes: 4
Views: 1903
Reputation: 71
After hours of facing the same problem and setting many many breakpoints I found a solution for my environment, I hope others can benefit from it:
inside Folder App_Start
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
var attr=new InitializeSimpleMembershipAttribute();
// here is the important part
attr.OnActionExecuting(new ActionExecutingContext());
filters.Add(attr);
}
}
Background: In my app I have 2 views:
I always had the problem in the following sitation:
At this point the method "OnActionExecuting" inside the class InitializeSimpleMembershipAttribute was not yet called (determined by setting breakpoints)!
But when I opened a View which doesn't require Authorization (i.e. /Account/Register) the Method "OnActionExecuting" was called. After this I could call /Task without errors.
So the solution was to make a "pseudocall" for "OnActionExecuting" on application-startup.
Upvotes: 1
Reputation: 17540
You should not need to init the database connection every time your HttpModule is called. Just do it once at application start up. Here is an article that explains how to use SimpleMembership for authentication/authorization of Web API calls. There is also a link to source code for the example project.
Upvotes: 0