SimpleMembership, MVC4, AuthorizeAttribute and Roles

帅比萌擦擦* 提交于 2019-11-30 02:45:11
Dylan Parry

I’ve found the solution (although I’m sure there’s a better way of doing it). Firstly, the database used by SimpleMembership isn’t initialized early enough, so I moved the line:

WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);

to the Global.asax file and made sure it got run as early as possible. The line of code can be found in Filters -> InitializeSimpleMembershipAttribute.cs , around line 41

Edit: it seems that this next bit isn’t necessary…

Secondly, the [InitializeSimpleMembership] attribute needs to be added to any class where membership might be an issue—for me that’s all of them, so I added the line:

filters.Add(new InitializeSimpleMembershipAttribute());

to the FilterConfig.cs file in the app_start folder.

These two simple changes seem to have fixed it. I’m sure there are some improvements I could make to the general workings of the SimpleMembership stuff included in MVC4 though—it doesn’t seem very well written (hard coded connection strings etc!), so it could be that these issues can be fixed by making the SimpleMembership stuff well written in the first place!

You shouldn't need to move the first line. I tested by just adding the filter

filters.Add(new InitializeSimpleMembershipAttribute());

Although if you are creating a site that requires you to login you can just have it on that one controller and not have to put it on all of the controllers.

The InitializeSimpleMembershipAttrribute generated by the Internet template for MVC 4 was designed for lazy loading of the SimpleMembership database in the event that the developer is not using forms authentication. If you are using forms authentication it is recommended to remove this filter and initialized it directly. This article describes how to do this.

In MVC4 I was able to add the annotation to my home controller and this error stopped coming up:

[InitializeSimpleMembership]

Also had to bring in the imports at the top as needed:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;

Check InitializeSimpleMembershipAttribute usage, web.config settings for SimpleProviders and may also consider making the InitializeSimpleMembershipAttribute an Authorization Filter specially when using Authorize(Roles="any")

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!