获得角色时ASP.Net MVC无法连接到数据库

时间:2018-07-07 06:31:55

标签: c# asp.net asp.net-mvc

我正在尝试编写ASP.Net MVC Web应用程序。几周前,我不得不重新格式化我的开发PC。当我恢复我的应用程序时,我开始遇到以前从未遇到的错误。该错误来自尝试在剃刀视图中获得用户角色。我已经在web.config中启用了角色管理器。我在startup.cs

中添加了角色
        ApplicationDbContext dbContext = new ApplicationDbContext();
        var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(dbContext));

        if (!roleManager.RoleExists("Visitor"))
        {
            var role = new IdentityRole();
            role.Name = "Visitor";
            roleManager.Create(role);
        }

,角色在数据库中。在我的布局中,导航栏中的链接仅对某些用户可用。运行此代码时将引发错误:

                @if(User.IsInRole("Visitor"))
                {
                    <li>Test</li>
                }

我也尝试过:

            @if (Roles.IsUserInRole(User.Identity.Name, "Vistor"))
            {
                <li>@Html.ActionLink("VistorArea", "Index", "Toolbox")</li>
            }

我得到的错误是

  

HttpException:无法连接到SQL Server数据库。

     

SqlException:建立与SQL Server的连接时发生与网络相关或特定于实例的错误。服务器未找到或无法访问。验证实例名称正确,并且已将SQL Server配置为允许远程连接。 (提供者:SQL网络接口,错误:26-指定服务器/实例时出错)

如果删除代码,我可以登录并注册,因此它可以连接到数据库。我试图创建一个新的清洁项目,并遇到同样的问题。如果有帮助,我可以上传干净的项目。感谢您的协助!

更新

因此,作为对我可以从数据库获取数据的问题的答复。当我运行此代码时:

        ApplicationDbContext db = new ApplicationDbContext();
        var test = db.Users.Find("8078ad14-6c09-4c83-baa2-9e14621ceb10");

        if(test.Email == "test@test.com")
        {
            ViewBag.TestString = "Success";
        }
        else
        {
            ViewBag.TestString = "Failure";
        }

成功。我的连接字符串如下所示:

    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-RoleTest-20180707020513.mdf;Initial Catalog=aspnet-RoleTest-20180707020513;Integrated Security=True"
  providerName="System.Data.SqlClient" />

1 个答案:

答案 0 :(得分:0)

从web.config检查数据库connectionString并检查IdentityModels.cs

Web.config

 <add name="DefaultConnection" connectionString="Data Source=.; Database=Your Database;uid=sa;password=Your Password;" providerName="System.Data.SqlClient" />

IdentityModels.cs

public ApplicationDbContext()
    : base("DefaultConnection", throwIfV1Schema: false)
{
}