问题
I'm having issues using the new identity system in MVC 5, my goal is to make use of the User.IsinRole("RoleName") on Views. For example:
@if(User.IsInRole("Administrator"))
{
<li>@Html.ActionLink("Admin", "Index", "Admin")</li>
}
This is placed in the main layout page which is hit when the application launches. On doing this, i'm getting the following error:
"An exception of type 'System.Web.HttpException' occurred in System.Web.dll but was not handled in user code
Additional information: Unable to connect to SQL Server database."
I have searched high and low for a solution to this, the common solution is to either include "[InitializeSimpleMembership]" at the top of the controller or initialise the database connection manually in application start. (With WebSecurity.InitializeDatabaseConnection). Both of these methods do not seem to be recognised by MVC 5.
I have also tried working around this by creating a bunch of messy code any time i return a view to populate the ViewBag with an IsAdmin boolean by using the Aspnet.Identity.UserManager to determine roles. Whilst this works it's not the way i feel i should be doing things.
It might be worth noting but i don't experience these issues accessing User.IsInRole on the backend, this definitely seems to be an initialization problem.
回答1:
I was having the same problem, however Stunt's answer wasn't working for me. Tried the answer to this question and that solved the issue.
For the lazy you can try adding this to your web.config file:
<system.webServer>
<modules>
<remove name="RoleManager" />
</modules>
</system.webServer>
回答2:
I managed to get around the problem by removing the following line from my Web Config:
<roleManager enabled="true" />
This was found when looking after comparing line for line on the following example code:
https://github.com/rustd/AspnetIdentitySample/tree/master/AspnetIdentitySample
回答3:
Create database on start up of the application. Add the following in the Global.ascx with your dbcontext.
using (FooContext db = new FooContext())
{
db.Database.CreateIfNotExists();
}
来源:https://stackoverflow.com/questions/19870397/mvc-5-isinrole-usage-on-razor-views-cannot-connect-to-database