我有一个运行在Windows 7/IIS 7.5上的ASP.NET 4.0应用程序,使用的是“ASP.NET v4.0 Classic”应用程序池,并配置为以Network Service身份运行。应用程序具有一个Application_EndRequest
处理程序,它连接到本地的SQL服务器实例。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)
当我浏览http://localhost/TestSite/default.aspx
(IIS中配置的默认文档)或任何其他.aspx页面时,不会抛出此异常;在这些情况下,应用程序正确地连接到 SQL Server 作为 "NT AUTHORITY\NETWORK SERVICE",这是一个有效的登录名。
为什么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
)似乎会引发一个嵌套的请求到 TestSite/default.aspx
(映射到 ASP.default_aspx
)。在 ASP.NET 完成处理 TestSite/default.aspx
后,它会模拟 "NT AUTHORITY\IUSR" 在继续处理对 TestSite/
的请求时。
更新: 我已将此问题提交到Microsoft Connect。