SimpleMembership MVC 4保持验证,但没有被认证 [英] SimpleMembership MVC 4 stays authenticated, but is not authenticated

查看:315
本文介绍了SimpleMembership MVC 4保持验证,但没有被认证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ASP.NET MVC 4 SimpleMembership开箱即用。

我设置的身份验证要求作为控制器与装饰 [授权(角色=用户)。

它工作正常,在离开网站时,未注销除外。下一次我回来, Request.IsAuthenticated 仍然是真实的,但是当我去一个观点,我得到 A与网络相关或实例建立SQL连接发生特异性误差。事实上,它看起来像它试图连接到本地数据库:SQLEx preSS数据库文件自动-creation错误 - 。在App_Data文件夹,但我有一个指向这个没有连接字符串,它是所有在Azure上的Sql

任何想法,这是什么?为什么它pretend中保持登录状态?而为什么试图创建一个数据库?

  ------------------------------------堆栈跟踪-------------------------------------------[SQLEXCEPTION(0x80131904):在与SQL Server建立连接时出现与网络相关的或特定于实例的错误。服务器未找到或无法访问。验证实例名称是否正确,以及SQL Server配置为允许远程连接。 (提供者:SQL网络接口,错误:26  - 错误定位服务器/实例指定)
   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException异常,布尔breakConnection,Action`1 wrapCloseInAction)5296071
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj,布尔callerHasConnectionLock,布尔asyncClose)558
   System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo,SqlInternalConnectionTds connHandler,布尔ignoreSniOpenTimeout,Int64的timerExpire,布尔值加密,布尔trustServerCert,布尔integratedSecurity布尔withFailover)5308555
   System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo,字符串NEWPASSWORD,SecureString的newSecurePassword,布尔ignoreSniOpenTimeout,TimeoutTimer超时,布尔withFailover)+145
   System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo,字符串NEWPASSWORD,SecureString的newSecurePassword,布尔redirectedUserInstance,SqlConnectionString connectionOptions,SqlCredential凭证,TimeoutTimer超时)889
   System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer超时,SqlConnectionString connectionOptions,SqlCredential凭证,字符串NEWPASSWORD,SecureString的newSecurePassword,布尔redirectedUserInstance)307
   System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity身份,SqlConnectionString connectionOptions,SqlCredential凭证,对象providerInfo,字符串NEWPASSWORD,SecureString的newSecurePassword,布尔redirectedUserInstance,SqlConnectionString userConnectionOptions)434
   System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions选项,DbConnectionPoolKey poolKey,对象poolGroupProviderInfo,池类DBConnectionPool,的DbConnection owningConnection,DbConnectionOptions USEROPTIONS)5311099
   System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(的DbConnection owningConnection,DbConnectionPoolGroup poolGroup,DbConnectionOptions USEROPTIONS)+38
   System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(的DbConnection owningConnection,TaskCompletionSource`1重试,DbConnectionOptions USEROPTIONS,DbConnectionInternal&安培;连接)5313314
   System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(的DbConnection outerConnection,DbConnectionFactory connectionFactory的,TaskCompletionSource`1重试,DbConnectionOptions USEROPTIONS)+143
   System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1重试)+83
   System.Data.SqlClient.SqlConnection.Open()+96
   System.Web.Management.SqlServices.GetSqlConnection(字符串服务器,用户字符串,字符串密码,布尔信赖,字符串的connectionString)+76[HttpException(0x80004005的):无法连接到SQL Server数据库]
   System.Web.Management.SqlServices.GetSqlConnection(字符串服务器,用户字符串,字符串密码,布尔信赖,字符串的connectionString)+131
   System.Web.Management.SqlServices.SetupApplicationServices(字符串服务器,用户字符串,字符串密码,布尔信赖,字符串的connectionString,数据库字符串,字符串dbFileName,SqlFeatures功能,布尔安装)+89
   System.Web.Management.SqlServices.Install(数据库字符串,字符串dbFileName,字符串的connectionString)+27
   System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(字符串fullFileName,DATADIR字符串,字符串的connectionString)+386


解决方案

我终于想通了这个问题!我有同样的问题时,我发现这个线程,但由于没有明确的答案,我不得不闲逛我自己。

会发生什么事是,UsersContext最终将履带的连接。通过完全绕过的UserContext,避免构造,连接将保持稳定。

请注意:我不是自动生成的简单的会员表了,所以我不知道这是否会制定出如果是这样的话

查看UsersContext在这里AccountModels.cs。你应该注释掉/删除code。

 公共类UsersContext:的DbContext
{
    公共UsersContext()
        :基地(YourDBContext)
    {
    }    公共DbSet<用户配置> {的UserProfiles获得;组; }
    公共DbSet< webpages_Membership> webpages_Memberships {搞定;组; }
    公共DbSet< UsersInRole> webpages_UsersInRoles {搞定;组; }
    公共DbSet<的角色和GT; webpages_Roles {搞定;组; }
}

从UsersContext的DbSets添加到您自己的上下文:

 公共类YourDBContext:的DbContext
{
    公共DbSet<&胡说GT;无聊症{搞定;组; }
    公共DbSet<&东西GT; {出头搞定;组; }    公共DbSet<用户配置> {的UserProfiles获得;组; }
    公共DbSet< webpages_Membership> webpages_Memberships {搞定;组; }
    公共DbSet< UsersInRole> webpages_UsersInRoles {搞定;组; }
    公共DbSet<的角色和GT; webpages_Roles {搞定;组; }    保护覆盖无效OnModelCreating(DbModelBuilder模型构建器)
    {
        modelBuilder.Conventions.Remove< PluralizingTableNameConvention>();
    }}

当然,你做的一切,你必须改变任何引用到UsersContext到YourDBContext后,即。

  UsersContext UC =新UsersContext();

变为

  YourDBContext YDB =新YourDBContext();

这样做的好处是,你不会有跟踪两个不同的DBContexts的。

I am using ASP.NET MVC 4 SimpleMembership "out of the box".

I set the authentication requirement as deco on the controllers with [Authorize(Roles = "User")].

It works fine, except when leaving the website without logging out. The next time I come back, Request.IsAuthenticated is still true, but when I go to a view, I get "A network-related or instance-specific error occurred while establishing a connection to SQL." In fact, it looks like it is trying to connect to a local database: "SQLExpress database file auto-creation error' - in the App_Data folder. But I have no connection string that points to this, it is all on Azure Sql.

Any idea what this is? And why does it pretend to stay logged in? And why the attempt to create a database?

------------------------------------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: 26 - Error Locating Server/Instance Specified)]
   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5296071
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +558
   System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover) +5308555
   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) +889
   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) +434
   System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +5311099
   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& connection) +5313314
   System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +143
   System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +83
   System.Data.SqlClient.SqlConnection.Open() +96
   System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +76

[HttpException (0x80004005): Unable to connect to SQL Server database.]
   System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +131
   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

解决方案

I finally figured out this problem! I was having the same problem when I found this thread, but since there was no definitive answer I had to poke around on my own.

What happens is that the UsersContext will eventually loose track of its connection. By bypassing the UserContext completely and avoiding the constructor, the connection will stay stable.

Note: I am not auto-generating the simple membership tables anymore so I am not sure if this will work out if that is the case.

See the UsersContext in the AccountModels.cs here. You should comment-out/delete this code.

public class UsersContext : DbContext
{
    public UsersContext()
        : base("YourDBContext")
    {
    }

    public DbSet<UserProfile> UserProfiles { get; set; }
    public DbSet<webpages_Membership> webpages_Memberships { get; set; }
    public DbSet<UsersInRole> webpages_UsersInRoles { get; set; }
    public DbSet<Role> webpages_Roles { get; set; }
}

Add the DbSets from UsersContext to your own context:

public class YourDBContext : DbContext
{
    public DbSet<Blah> Blahs{ get; set; }
    public DbSet<Something> Somethings { get; set; }

    public DbSet<UserProfile> UserProfiles { get; set; }
    public DbSet<webpages_Membership> webpages_Memberships { get; set; }
    public DbSet<UsersInRole> webpages_UsersInRoles { get; set; }
    public DbSet<Role> webpages_Roles { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }

}

Of course after you do all that you must change any references to the UsersContext into YourDBContext, i.e.

UsersContext uc = new UsersContext();

Becomes

YourDBContext ydb = new YourDBContext();

The added benefit of doing this is that you won't have to keep track of two different DBContexts.

这篇关于SimpleMembership MVC 4保持验证,但没有被认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆