![](/img/trans.png)
[英]ASP.NET MVC SQL Server not accesable when trying to authenticate or access roles?
[英]SQL Server timeout when requesting roles in MVC5.net application
我正在使用MVC5.NET框架和Razor View Engine用C#開發Web應用程序。 為了進行身份驗證,我在開發時使用ASP.NET Identity(MVC5的標准配置)和SQL Server Express 2012進行數據存儲。 目前,SQL Server實例與應用程序在同一台計算機上運行。 我正在Visual Studio 2012中進行開發,並使用Nuget安裝了Identity。
我正在我的應用程序中實現角色身份驗證,但是由於某些神秘的原因,當應用程序到達身份驗證屬性(可能是Authorize
屬性或自定義IAuthenticationFilter
)時,SQL Server超時。 一切正常,可以登錄,可以請求,添加和更新數據,可以注冊新帳戶,但是每當嘗試訪問角色時,SQL Server都會拋出HttpException
異常: Unable to connect to SQL Server database.
這是我的自定義IAuthenticationFilter
的代碼:
public class RoleAuthenticationFilter : ActionFilterAttribute,IAuthenticationFilter
{
public String AllowedRole { get; set; }
public void OnAuthentication(AuthenticationContext filterContext)
{
if (filterContext.Principal.Identity.IsAuthenticated)
{
if (!filterContext.Principal.IsInRole(AllowedRole))
{
filterContext.Result = new HttpUnauthorizedResult();
//throw new HttpException(403, "Unauthorized access");
}
}
else
{
filterContext.Result = MVC.Account.Login();
//throw new HttpException(403, "Unauthorized access");
}
}
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
filterContext.Result = MVC.Account.Login();
}
}
我這樣使用它: [RoleAuthentificationFilter(AllowedRole = "User")]
在RoleAuthenticationFilter
,在調試時,我注意到該異常是在IsInRole
調用上而不是之前拋出的。 我檢查了AuthenticationContext filterContext
實例,發現它包含了所需的所有信息(例如當前用戶所處的角色。)
我的瀏覽器顯示以下異常:
建立與SQL Server的連接時發生與網絡相關或特定於實例的錯誤。 服務器未找到或無法訪問。 驗證實例名稱正確,並且已將SQL Server配置為允許遠程連接。 (提供者:SQL網絡接口,錯誤:26-查找指定的服務器/實例時出錯)。
我通過以下方法解決了這個問題:
出於某種原因,實際上,創建用戶(及其表,包括角色的表)不需要任何指示,只是存在“ DefaultConnection”。
盡管如此,當您要授權角色時,需要向應用程序提供RoleProvider將使用的連接字符串的名稱。
因此,您可能需要將以下內容添加到web.config文件中(部分)。
<profile defaultProvider="DefaultProfileProvider">
<providers>
<add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider" connectionstringname="DefaultConnection" applicationname="/">
</add>
</providers>
</profile>
<membership defaultProvider="DefaultMembershipProvider">
<providers>
<add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider" connectionstringname="DefaultConnection" enablepasswordretrieval="false"
enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>
<roleManager defaultProvider="DefaultRoleProvider">
<providers>
<add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider" connectionstringname="DefaultConnection" applicationname="/" />
</providers>
</roleManager>
我是由平常的Scott Hanselman撰寫的一篇文章得到這個想法的,但是他肯定已經使用了舊版本的ASP.net表單身份驗證引擎,因為web.config部分的拼寫都是錯誤的:
希望我能對您有所幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.