【问题标题】:SQLExpress database file auto-creation error, Authorizing with RolesSQLExpress 数据库文件自动创建错误,使用角色授权
【发布时间】:2015-07-06 15:44:36
【问题描述】:

标题类型描述了问题。我正在尝试使用角色授权,并且我已成功创建用户和角色。我还可以为用户分配角色。我已验证以下操作确实会修改数据库表。但是,当我在控制器方法上使用角色授权时,我会遇到某种 SQL Server 超时。

例如:

    [Authorize(Roles="Admin")]
    public ActionResult Admin()
    {
        ViewBag.Message = "Your admin page.";
        var context = new IdentityDbContext();
        IDbSet<IdentityRole> roles = context.Roles;
        List<string> roleList = new List<string>();
        foreach (IdentityRole role in roles)
            roleList.Add(role.Name);
        ViewBag.Roles = roleList;
        IDbSet<IdentityUser> users = context.Users;
        List<string> userList = new List<string>();
        foreach (IdentityUser user in users)
            userList.Add(user.UserName);
        ViewBag.Users = userList;
        return View();
    }

但这会随着响应超时:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

任何帮助将不胜感激。您可以在下面找到我的 SQL 连接字符串以及创建角色和将用户添加到角色的方法。谢谢

SQL 连接字符串:

  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=192.168.10.160,1433;Initial Catalog=PriceConfigurator;User Id=PriceConfiguratorDBA;Password=*********" providerName="System.Data.SqlClient" />
  </connectionStrings>

角色/用户管理:

    [HttpPost]
    public ActionResult AddToUser(FormCollection collection)
    {
        try
        {
            var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
            var userManager = new UserManager<Microsoft.AspNet.Identity.EntityFramework.IdentityUser>(new UserStore<IdentityUser>(new ApplicationDbContext()));
            var context = new IdentityDbContext();
            var userName = collection["AddUserRoleUsername"];
            IdentityUser user = context.Users.Where(x => x.UserName == userName).FirstOrDefault();
            var roleName = collection["AddUserRoleNameList"];
            userManager.AddToRole(user.Id, roleName);
            return Json(userName + " added to " + roleName, JsonRequestBehavior.DenyGet);
        }
        catch (Exception ex)
        {
            return Json("Error occured: " + ex.Message, JsonRequestBehavior.DenyGet);
        }
    }

    [HttpPost]
    public ActionResult RemoveFromUser(FormCollection collection)
    {
        try
        {
            var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
            var userManager = new UserManager<Microsoft.AspNet.Identity.EntityFramework.IdentityUser>(new UserStore<IdentityUser>(new ApplicationDbContext()));
            var context = new IdentityDbContext();
            var userName = collection["RemoveUserRoleUsername"];
            IdentityUser user = context.Users.Where(x => x.UserName == userName).FirstOrDefault();
            var roleName = collection["RemoveUserRoleNameList"];
            userManager.RemoveFromRole(user.Id, roleName);
            return Json(userName + " removed from " + roleName, JsonRequestBehavior.DenyGet);
        }
        catch (Exception ex)
        {
            return Json("Error occured: " + ex.Message, JsonRequestBehavior.DenyGet);
        }
    }

我还尝试在我的 web.config 中覆盖成员资格提供程序

 <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <membership>
      <providers>
        <clear/>
        <add name="AspNetSqlRoleProvider" connectionStringName="DefaultConnection" applicationName="/" type="System.Web.Security.SqlRoleProvider"/>
        <add name="AspNetSqlProfileProvider" connectionStringName="DefaultConnection" applicationName="/" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
        <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" applicationName="/" requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="10" passwordStrengthRegularExpression="" />
  </providers>
</membership>
<roleManager enabled="true">
</roleManager>

【问题讨论】:

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


    【解决方案1】:

    这里有一些事情要检查:

    Make sure your database engine is configured to accept remote connections:
        Start > All Programs > SQL Server 2005 > Configuration Tools > SQL Server Surface Area Configuration
        Click on Surface Area Configuration for Services and Connections
        Select the instance that is having a problem > Database Engine > Remote Connections
        Enable local and remote connections
        Restart instance
    

    您也可以查看此链接7 things to check to resolve "A network-related or instance-specific error occurred while establishing a connection to SQL Server…"

    You may need to create an exception on the firewall for the SQL Server instance and port you are using:
        Start > Run > Firewall.cpl
        Click on exceptions tab
        Add sqlservr.exe
            typically located in C:\Program Files (x86)\Microsoft SQL Server\MSSQL.x\MSSQL\Bin - check your installs for the actual folder path
        Add the port (default is 1433)
        Check your connection string as well
    Check if your SQL server services is up and running properly:
        Go to All Programs > Microsoft SQL Server 2008 > Configuration Tools > SQL Server Configuration Manager > SQL Server Services
        Check to make sure SQL Server service status is Running.
    Ensure that your remote server is in the same network:
        Open your command prompt and Run sqlcmd -L to ascertain if your server is included in your network list.
        See More At: [Using sqlcmd – Detect Installed SQL Server on Network][1]
    
    
    
    Enable TCP/IP in SQL Server Configuration:
        Go to All Programs > Microsoft SQL Server 2008 > Configuration Tools > SQL Server Configuration Manager > Select TCP/IP.
        Right click and select enable
    

    你也可以试试这个链接fix-error-provider-named-pipes-provider-error-40-could-not-open-a-connection-to-sql-server-microsoft-sql-server-error

    【讨论】:

    • 感谢您的信息。我已经验证了您建议的信息。另外,我应该指出,我可以为这个数据库创建用户和角色。我什至可以毫无问题地使用 [Authorize] 属性。当我附加角色属性时会出现问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    • 2015-11-25
    • 2020-06-03
    • 1970-01-01
    • 2013-12-21
    • 2011-04-02
    相关资源
    最近更新 更多