【问题标题】:MSSQLLocalDb - How to create custom authentication with localDb connection in ASP.Net MVC?MSSQLLocalDb - 如何在 ASP.Net MVC 中使用 localDb 连接创建自定义身份验证?
【发布时间】:2016-11-10 06:25:39
【问题描述】:

我正在尝试使用 MSSQLLocalDb 创建自己的身份验证服务。我已使用此连接字符串来实例化 IdentityDbContext 类的本地实例。

connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-VeriSystems-20161025123601.mdf;Initial Catalog=aspnet-VeriSystems-20161025123601;Integrated Security=True;MultipleActiveResultSets=True

但是每当我将我的项目发布到 IIS localhost 时,我都无法执行登录服务。我得到了这个错误

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: 50 - Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details.
    )
Stack Trace: 


[SqlException (0x80131904): 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: 50 - Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details.
)]
   System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling) +1418
   System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +470
   System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +70
   System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +945
   System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +114
   System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +1637
   System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +117
   System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) +267
   System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +318
   System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) +132
   System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +246
   System.Data.SqlClient.SqlConnection.Open() +122
   System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) +104
   System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext) +442
   System.Data.Entity.SqlServer.<>c__DisplayClass33.<UsingConnection>b__32() +562
   System.Data.Entity.SqlServer.<>c__DisplayClass1.<Execute>b__0() +16
   System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func`1 operation) +229
   System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action`1 act) +916
   System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable`1 commandTimeout, DbConnection sqlConnection, String createDatabaseScript) +111
   System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection) +203
   System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection) +129
   System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase) +172
   System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration) +110
   System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func`3 createMigrator, ObjectContext objectContext) +118
   System.Data.Entity.Database.Create(DatabaseExistenceState existenceState) +284
   System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context) +185
   System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action) +72
   System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() +502
   System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input) +177
   System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action) +273
   System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +38
   System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +77
   System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext() +21
   System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider() +56
   System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync(IQueryable`1 source, Expression`1 predicate, CancellationToken cancellationToken) +199
   System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync(IQueryable`1 source, Expression`1 predicate) +163
   Microsoft.AspNet.Identity.EntityFramework.<GetUserAggregateAsync>d__6c.MoveNext() +503
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +14139120
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +62
   Microsoft.AspNet.Identity.CultureAwaiter`1.GetResult() +48
   Microsoft.AspNet.Identity.Owin.<PasswordSignInAsync>d__29.MoveNext() +410
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +14139120
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +62
   VeriSystems.Controllers.<Login>d__11.MoveNext() +373
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +14139120
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +62
   System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +93
   System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeAsynchronousActionMethod>b__36(IAsyncResult asyncResult) +22
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +42
   System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +72
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +386
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +42
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +38
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +186
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +38
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +65
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +53
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +36
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +38
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +44
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +65
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +38
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +399
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +157

我已使用此代码来实现 IdentityDbContext

 public class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }

我想知道我做错了什么。以下列表是我尝试过的事情:

  1. 我尝试配置 IIS 虚拟目录但没有成功,即尝试将应用程序池更改为 LocalSystem 或 LocalService 而不是 ApplicationPoolIdentity。

2.我更改了虚拟目录以允许桌面用户和 IIS 主机具有读取和执行权限。

将不胜感激。

【问题讨论】:

  • 您在 SSMS 中是否打开了与数据库的连接?
  • 首先仔细检查您是否安装了 SqlServer Local DB,如果是,II 会建议安装 SSMS 并确认您可以连接到 SSMS 中 localdb 上的该数据库。 (即证明它适用于某事)。
  • IIS connecting to LocalDB的可能重复

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


【解决方案1】:

将您的连接字符串与此处的一个进行比较(确实有效):

Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|Project.mdf

| 和数据文件名之间没有反斜杠。

【讨论】:

    【解决方案2】:

    问题在于 MSSqlLocalDb 的私有实例未通过 IIS 共享。为了实现这一点,我们必须执行以下步骤:

    1. 在管理员命令提示符下执行以下命令

      sqllocaldb 共享 mssqllocaldb '您选择的名称'

    2. 通过在您选择的数据库中的 Visual Studio 的 SQL Server 对象资源管理器中执行此查询,为托管应用程序池创建自定义登录名

    从windows创建登录[IISAPPPOOL\'Application Pool name'];

    exec sp_addsrvrolemember N'IISAPPPOOL\'应用程序池名称', sysadmin

    1. 修改web.config文件中的连接字符串,数据源为

      connectionString="Data Source=(LocalDb).\'Instance name';AttachDbFilename=|DataDirectory|\project.mdf;Initial Catalog=project;Integrated Security=True;MultipleActiveResultSets=True

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多