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

人盡茶涼 提交于 2021-02-06 10:12:37

问题


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

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