I need to get an instance of the application's MembershipProvider from within a controller. I have a custom membership implementation that has a custom User property that describes the logged in user. At the heart of the issue is that I need to retrieve this User object.
My application has done a skeletal implementation of the MembershipProvider, but it works fine and correctly validates users that attempt to login or create a new account. Be开发者_运维百科cause of that, I have kept the default implementation of the AccountController that comes out of the box for an ASP .NET MVC application.
If you need anymore details, I would be happy to provide them.
I'm guessing your MembershipProvider is registered in web.config. If so, you can use static property System.Web.Security.Membership.Provider
.
If you create a new ASP.NET MVC project in Visual Studio, it will automatically create a controller called AccountController
for you. This controller provides an example of how you are supposed to access the MembershipProvider in ASP.NET MVC.
In short, it promotes Dependency Injection (DI) and loose coupling by hiding the MembershipProvider behind the IMembershipService
interface.
The class AccountMembershipService
implements IMembershipService
as an Adapter of MembershipProvider
.
You can inject an instance of IMembershipService
into any controller that needs it, just like the AccountController
does.
I agree with Mike that this is the standard way to do this, but to mitigate the confusion of having to cast your Provider each time, you could create a base controller that all of your controllers inherit from and have a protected property with a getter that casts it once. This will accomplish better code re-use and if you ever change your membership provider you'll only have to do it in once place.
精彩评论