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

标签 c# asp.net azure

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

我正在尝试添加角色并为用户提供在 singup 上选择 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 上的数据库。

最佳答案

<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>

但首先要确保您的数据库已具备默认提供程序运行所需的所有表和 SQL 过程,方法是安装 aspnet_regsql ( see this link )。

关于c# - Roles.RoleExists() 导致 SQL 网络接口(interface),错误 : 26,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26587561/

相关文章:

c# - WPF 数据绑定(bind)标签内容

c# - 对实现 IEnumerator 的类进行序列化

azure - 如何在 IoT 即插即用 DTDL 模型中设置设备孪生的所需属性和报告属性

azure - 服务器宕机时如何设置网站默认页面?

javascript - 返回 View MVC/Javascript/.NET Core 时出现问题

c# - 为什么 Moq 看不到在 .Select 方法中调用此方法?

c# - 我可以使用什么来进行本地 MySQL 测试?

asp.net - 如何从 Asp.Net 那样的堆栈跟踪中获取 "Source Error"?

c# - 在 RDLC 中使用多个数据集

azure - 如何让 Cosmos DB 模拟器在计算机启动/重新启动时自动启动