1

我们有时会在 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
...

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

4

2 回答 2

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>
于 2013-05-28T15:36:52.243 回答
0

您使用的是什么会员系统,是否已初始化?如果您使用的是 SimpleMembership,请尝试:

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

在此处使用 simplemembership 的新 MVC 4 Internet 模板中基于角色的身份验证的更多信息

于 2013-05-23T07:58:38.730 回答