Roles.RoleExists()导致SQL网络接口,错误:26

本文关键字:错误 网络接口 SQL RoleExists 导致 Roles | 更新日期: 2023-09-27 18:28:07

我有一个带有帐户控制器的ASP.NET MVC5 Internet应用程序。

我正在尝试添加角色,并让用户在挑选时在3个角色之间进行选择,我的注册方法如下:

        [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            if (!Roles.RoleExists("user"))
            {
                Roles.CreateRole("user");
            }
            if (!Roles.RoleExists("superuser"))
            {
                Roles.CreateRole("superuser");
            }
            if (!Roles.RoleExists("admin"))
            {
                Roles.CreateRole("admin");
            }
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {

                var currentUser = UserManager.FindByName(user.UserName);
                string userType = null;
                switch (model.Type)
                {
                    case 1:
                        userType = "user";                         
                        break;
                    case 2:
                        userType = "superuser";
                        break;
                    case 3:
                        userType = "admin";
                        break;
                    default:
                        return View(model);
                        break;
                }

                var roleresult = UserManager.AddToRole(currentUser.Id,userType);
                return RedirectToAction("Index", "Home");
            }
            AddErrors(result);
        }
        return View(model);
    }

当我尝试注册,代码到达if (!Roles.RoleExists("user"))时,网站会挂起大约10秒,我会得到以下错误:

SQL Network Interfaces, error: 26 

    [SqlException (0x80131904): Der opstod en netværksrelateret eller forekomstspecifik fejl, da det blev forsøgt at oprette forbindelse til SQL Server. Serveren blev ikke fundet, eller der var ikke adgang til den. Kontroller, at forekomstnavnet er korrekt, og at SQL Server er konfigureret til at tillade fjernforbindelser. (provider: SQL Network Interfaces, error: 26 - Fejl ved søgning efter angivet server/forekomst.)]
   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5340655
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +244
   System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover) +5350915
   System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) +145
   System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) +922
   System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) +307
   System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData) +518
   System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +5353725
   System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions) +38
   System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) +5355926
   System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +146
   System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +16
   System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) +94
   System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +110
   System.Data.SqlClient.SqlConnection.Open() +96
   System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +75
[HttpException (0x80004005): Der kan ikke oprettes forbindelse til SQL Server-databasen.]
   System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +130
   System.Web.Management.SqlServices.SetupApplicationServices(String server, String user, String password, Boolean trusted, String connectionString, String database, String dbFileName, SqlFeatures features, Boolean install) +89
   System.Web.Management.SqlServices.Install(String database, String dbFileName, String connectionString) +27
   System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString) +386

我不知道如何把错误信息改成英语。

在web.config中,我将<roleManager enabled="true" />添加到system.web,我的连接字符串如下所示:

<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=lmjzf199gd.database.windows.net;Initial Catalog=lenioDb;Persist Security Info=True;User ID=lenio;Password=*******;Integrated Security=False;Encrypt=False;TrustServerCertificate=False;" providerName="System.Data.SqlClient" />

显然,密码在连接字符串中没有设置为"*******"。

我用的是azure上的数据库。

Roles.RoleExists()导致SQL网络接口,错误:26

<roleManager enabled="true">下,您必须指定角色提供程序以及正确的连接字符串(这就是问题所在)。示例:

<roleManager enabled="true" cacheRolesInCookie="true" cookieName=".ASPROLES" defaultProvider="DefaultRoleProvider">
    <providers>
        <add connectionStringName="DefaultConnection" applicationName="/" name="DefaultRoleProvider"
        type="System.Web.Security.SqlRoleProvider"/>
    </providers>
</roleManager>

但是,首先通过安装aspnet_regsql(请参阅此链接),确保您的数据库已经具备默认提供程序工作所需的所有表和sql过程。