我找到的解决方案如下:
在 global.asax.cs 中
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
if (HttpContext.Current.Session != null)
{
if (System.Configuration.ConfigurationManager.AppSettings["anonymous"] == "true")
{
HttpContext.Current.User = new GenericPrincipal(new GenericIdentity("DOMAIN\\Harry-Potter"), new string[] { });
}
}
}
使用 Build => 配置管理器创建了一个构建配置文件.. =>(在 Active solution configuration 下是一个下拉菜单,您可以在其中添加新的)
右键单击 web.config 并选择“添加配置转换”
在 web.[您的个人资料].config 中:
<appSettings>
<add key="anonymous" value="true" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />
使用 web.debug.config 和 web.[my build profile].config 对 web.config 的转换在您出于某种原因发布之前不适用。要在每次构建时都可以使用转换,您可以执行以下操作。
将 web.config 复制到 web.base(web.base 不存在,所以只需 copy web.config web.base
打开您的 Web 应用程序 csproj 文件(与 web.config 和 web.base 相同的目录)在末尾添加/编辑以下 2 行。
<PropertyGroup>
<PostBuildEvent>"$(MSBUILDBINPATH)\msbuild" "$(ProjectPath)" /t:Transform /p:Configuration=$(ConfigurationName);Platform=AnyCPU</PostBuildEvent>
</PropertyGroup>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target> -->
<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.Tasks.dll" />
<Target Name="Transform">
<MakeDir Directories="bin" Condition="!Exists('bin')" />
<TransformXml Source="Web.base" Transform="Web.$(Configuration).config" Destination="Web.config" StackTrace="true" />
</Target>
在 web.base 中:
<appSettings>
<add key="anonymous" value="false" />
每次构建时都会重新编写 web.config。
现在,当您切换构建配置文件时,您可以拥有应用程序的真实用户或模拟用户身份(也可以方便地测试其他用户配置文件)。
在 C:\Users[我的用户]\Documents\IISExpress\config\applicationhost.config 中
我更改了一些设置以允许匿名用户,如果不是 IIS express 将不允许匿名用户。
<anonymousAuthentication enabled="true" userName="" />