我在“ASP.NET v4.0 Classic”应用程序池中运行在 Windows 7 / IIS 7.5 上的 ASP.NET 4.0 应用程序,该应用程序配置为作为网络服务运行。该应用程序有一个Application_EndRequest
连接到本地 SQL Server 实例的处理程序。SQL 连接字符串指定Integrated Security=SSPI
. Web.config没有<identity impersonate="true" />
. _
当我浏览到 时http://localhost/TestSite/
,会引发以下异常:
System.Data.SqlClient.SqlException (0x80131904): Login failed for user 'NT AUTHORITY\IUSR'.
...
at System.Data.SqlClient.SqlConnection.Open()
at Global.Application_EndRequest(Object sender, EventArgs e)
当我浏览到(在 IIS 中配置的默认文档)或任何其他 .aspx 页面时,不会引发此异常;http://localhost/TestSite/default.aspx
在这些情况下,应用程序作为“NT AUTHORITY\NETWORK SERVICE”正确连接到 SQL Server,这是一个有效的登录。
即使禁用了模拟,为什么 ASP.NET 会在 EndRequest 中模拟“NT AUTHORITY\IUSR”?这是 ASP.NET 中的错误吗?
以下 Global.asax.cs 文件演示了该问题:
public class Global : HttpApplication
{
public Global()
{
this.BeginRequest += delegate { Log("BeginRequest"); };
this.PreRequestHandlerExecute += delegate { Log("PreRequestHandlerExecute"); };
this.PostRequestHandlerExecute += delegate { Log("PostRequestHandlerExecute"); };
this.EndRequest += delegate { Log("EndRequest"); };
}
protected void Application_EndRequest(Object sender, EventArgs e)
{
try
{
using (SqlConnection connection = new SqlConnection("Server=.;Integrated Security=SSPI"))
{
connection.Open();
}
}
catch (Exception ex)
{
Trace.WriteLine(ex);
}
}
private static void Log(string eventName)
{
HttpContext context = HttpContext.Current;
Type impersonationContextType = typeof(HttpContext).Assembly.GetType("System.Web.ImpersonationContext", true);
Trace.WriteLine(string.Format("ThreadId={0} {1} {2} Impersonating={3}",
Thread.CurrentThread.ManagedThreadId,
context.Request.Url,
eventName,
impersonationContextType.InvokeMember("CurrentThreadTokenExists", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.GetProperty, null, context, null)));
}
}
这是跟踪输出:
ThreadId=3 http://localhost/TestSite/ BeginRequest Impersonating=False
ThreadId=3 http://localhost/TestSite/ PreRequestHandlerExecute Impersonating=False
ThreadId=7 http://localhost/TestSite/default.aspx BeginRequest Impersonating=False
ThreadId=7 http://localhost/TestSite/default.aspx PreRequestHandlerExecute Impersonating=False
ThreadId=7 http://localhost/TestSite/default.aspx PostRequestHandlerExecute Impersonating=False
ThreadId=7 http://localhost/TestSite/default.aspx EndRequest Impersonating=False
ThreadId=7 http://localhost/TestSite/ PostRequestHandlerExecute Impersonating=True
ThreadId=7 http://localhost/TestSite/ EndRequest Impersonating=True
System.Data.SqlClient.SqlException (0x80131904): Login failed for user 'NT AUTHORITY\IUSR'.
...
at System.Data.SqlClient.SqlConnection.Open()
at Global.Application_EndRequest(Object sender, EventArgs e)
请注意,对TestSite/
(映射到DefaultHttpHandler
)的请求似乎产生了对(映射到)的嵌套请求。ASP.NET 完成处理后,它会在继续处理对.TestSite/default.aspx
ASP.default_aspx
TestSite/default.aspx
TestSite/
更新:我已将此问题提交给Microsoft Connect。