在Azure上运行MVC4时出错

时间:2013-05-23 07:38:32

标签: sql-server asp.net-mvc asp.net-mvc-4 azure azure-sql-database

我们有时会在Azure上启动MVC4站点时出错。从未在本地服务器上看到这些错误。在将数据库和应用程序部署到Azure之后,如果请求授权并且在站点上不活动一段时间之后(由于超时可能导致错误),则会在主页启动时出现问题。代码简单如下所示:

[InitializeSimpleMembership]
[Authorize(Roles = "Administrator")]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

请求主页有时会失败:

[Win32Exception (0x80004005): Access is denied]

[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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)]
....
System.Data.SqlClient.SqlConnection.Open() +96
System.Web.DataAccess.SqlConnectionHolder.Open(HttpContext context, Boolean revertImpersonate) +88
System.Web.DataAccess.SqlConnectionHelper.GetConnection(String connectionString, Boolean revertImpersonation) +239
System.Web.Security.SqlRoleProvider.GetRolesForUser(String username) +762
WebMatrix.WebData.SimpleRoleProvider.GetRolesForUser(String username) +54
...

如何防止此(超时)错误?谢谢你的帮助!

2 个答案:

答案 0 :(得分:7)

将以下行从InitializeSimpleMembershipAttribute.cs(过滤器)移至AuthConfig.cs:

WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);

所以代码看起来像:

public static class AuthConfig
{
    public static void RegisterAuth()
    {
        WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
        ...

也许您需要在web.config(部分system.web)中使用以下内容:

<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
 <providers>
  <clear/>
  <add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>
 </providers>
</roleManager>
<membership defaultProvider="SimpleMembershipProvider">
 <providers>
  <clear/>
  <add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
 </providers>
</membership>

答案 1 :(得分:0)

您使用的是什么会员制并已初始化?如果您正在使用SimpleMembership,请尝试:

[Authorize(Roles = "Administrator")]
[InitializeSimpleMembership]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

有关此内容的更多信息Role based authentication in the new MVC 4 Internet template using simplemembership