Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 5 IsInRole Usage on Razor Views: Cannot connect to Database

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.

like image 615
Stunt Avatar asked Nov 08 '13 23:11

Stunt


1 Answers

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>
like image 149
grimurd Avatar answered Sep 20 '22 13:09

grimurd