解惑

解己之惑,解人之惑

日:2009年7月28日

单元测试以Windows集成方式认证的Web Service

如果直接引用Web Service写单元测试,运行以Windows集成方式认证并且不允许匿名访问的Web Service,那么运行的时候会报错,因为权限不够,可能是因为Visual Studio在运行的时候是以匿名用户的身份运行的,而非OS的用户身份,这样的情况需要写些代码来使用OS的用户身份:
        [TestInitialize]
        public void SetUp()
        {
            var basicHttpBinding = new BasicHttpBinding();

            basicHttpBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;

            basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;

            var endpoint = new EndpointAddress("http://localhost/IntegrationService/IntegrationService.asmx");

            _client = new IntegrationServiceSoapClient(basicHttpBinding, endpoint);
            _client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;

            _client.ChannelFactory.Credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
        }
代码中的EndpointAddress和IntegrationServiceSoapClient要换成你自己的Web Service的对应内容。

更新:
如果按照 Windows平台应用的运行身份的更新中所说的指定用户,那么这里的单元测试就不需要这样麻烦了,直接new一个Client就可以了。

MSBuild没有那么难

希望在脱离Visual Studio的情况下也可以编译我们的.Net工程,根据网上的资料发现MSBuild可以使用sln和*.*proj文件,而sln就是Visual Studio的Solution文件,而每个project都有一个csproj文件,最开始的时候使用MSBuild编译发现不行,说MSBuild支持的文件版本不对,后来发现MSBuild配置的路径是.Net2.0.5的路径,而我们现在使用的其实是3.5版本的.Net,修改MSBuild的路径后发现可以了。
所以如果使用Visual Studio创建的工程,其实它就是用的MSBuild在进行Solution和Project的编译,不用自己再手工写build文件了。

© 2025 解惑

本主题由Anders Noren提供向上 ↑