none
WCF 在IIS部署中的问题~! 急... RRS feed

  • 问题

  • IMySimpleService.cs 代码如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.Text;

    namespace ServerWcfService.ServiceContracts
    {
        [ServiceContract]
        public interface IMySimpleService
        {
            [OperationContract]
            string PrintMessage(string message);
        }
    }

     


    MySimpleService.svc 文件代码如下:

     

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.Text;
    using ServerWcfService.ServiceContracts;

    namespace ServerWcfService.Services
    {
           public class MySimpleService : IMySimpleService
        {
            public string PrintMessage(string msg)
            {
                msg = "PrintMessage(" + msg + ")";
                Console.WriteLine(msg);
                return msg;
            }
        }
    }

    CustomUserNameValidator.cs 代码如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IdentityModel.Selectors;
    using System.IdentityModel.Tokens;

    namespace ServerWcfService.CustomValidators
    {
        public class MyCustomValidator : UserNamePasswordValidator
        {
            /// <summary>
            /// Validates the user name and password combination.
            /// </summary>
            /// <param name="userName">The user name.</param>
            /// <param name="password">The password.</param>
            public override void Validate(string userName, string password)
            {
                // validate arguments
                if (string.IsNullOrEmpty(userName))
                    throw new ArgumentNullException("userName");
                if (string.IsNullOrEmpty(password))
                    throw new ArgumentNullException("password");

                // check if the user is not xiaozhuang
                if (userName != "test" || password != "123456")
                    throw new SecurityTokenException("用户名或者密码错误!");
            }
        }

    }

    Web.config 配置如下:
    <?xml version="1.0"?>
    <!--
        注意: 除了手动编辑此文件以外,
        还可以使用 Web 管理工具来配置应用程序的设置。
        可以使用 Visual Studio 中的“网站”->“Asp.Net 配置”选项。
        设置和注释的完整列表在
        machine.config.comments 中,该文件通常位于
        \Windows\Microsoft.Net\Framework\v2.x\Config
    -->
    <configuration> 
     <system.serviceModel>
      <bindings>
       <wsHttpBinding>
        <binding name="mySecureBinding">
         <security mode="Message">
          <message clientCredentialType="UserName"/>
         </security>
        </binding>
       </wsHttpBinding>
      </bindings>
      <services>
       <service behaviorConfiguration="ServerWcfService.Services.MySimpleServiceBehavior" name="ServerWcfService.Services.MySimpleService">
        <endpoint address="" binding="wsHttpBinding" contract="ServerWcfService.ServiceContracts.IMySimpleService" bindingConfiguration="mySecureBinding">
         <identity>
          <dns value="localhost"/>
         </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
       </service>
      </services>
      <behaviors>
       <serviceBehaviors>
        <behavior name="ServerWcfService.Services.MySimpleServiceBehavior">
         <serviceMetadata httpGetEnabled="true"/>
         <serviceDebug includeExceptionDetailInFaults="false"/>
         <serviceCredentials>
          <serviceCertificate findValue="localhost" x509FindType="FindBySubjectName" storeLocation="LocalMachine" storeName="My"/>
          <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="ServerWcfService.CustomValidators.MyCustomValidator,ServerWcfService"/>
         </serviceCredentials>
        </behavior>
       </serviceBehaviors>
      </behaviors>
     </system.serviceModel>
    </configuration>

     

    以上代码在vs2008下按F5调试模式可以正确执行,但我把该项目文件放到IIS里面,建了一个站点service.xxx.com,则提示"句柄无效",这是什么原因呢?我想把这服务部署到IIS下,供远程通过授权用户名和密码来调用!

    句柄无效。

    说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。

    异常详细信息: System.Security.Cryptography.CryptographicException: 句柄无效。

    源错误:

    执行当前 Web 请求期间生成了未处理的异常。可以使用下面的异常堆栈跟踪信息确定有关异常原因和发生位置的信息。

    堆栈跟踪:

    [CryptographicException: 句柄无效。
    ]
       System.Security.Cryptography.Utils.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer) +7710462
       System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType, CspParameters parameters, Boolean randomKeyContainer, Int32 dwKeySize, SafeProvHandle& safeProvHandle, SafeKeyHandle& safeKeyHandle) +67
       System.Security.Cryptography.RSACryptoServiceProvider.GetKeyPair() +83
       System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 dwKeySize, CspParameters parameters, Boolean useDefaultKeySize) +226
       System.Security.Cryptography.RSACryptoServiceProvider..ctor(CspParameters parameters) +9
       System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey() +202
       System.ServiceModel.Security.SecurityUtils.EnsureCertificateCanDoKeyExchange(X509Certificate2 certificate) +69
    
    [ArgumentException: The certificate 'CN=client.service.jinri.web' must have a private key that is capable of key exchange. The process must have access rights for the private key.]
       System.ServiceModel.Security.SecurityUtils.EnsureCertificateCanDoKeyExchange(X509Certificate2 certificate) +11590330
       System.ServiceModel.Security.ServiceCredentialsSecurityTokenManager.CreateServerX509TokenProvider() +36
       System.ServiceModel.Security.ServiceCredentialsSecurityTokenManager.CreateLocalSecurityTokenProvider(RecipientServiceModelSecurityTokenRequirement recipientRequirement) +63
       System.ServiceModel.Security.ServiceCredentialsSecurityTokenManager.CreateSecurityTokenProvider(SecurityTokenRequirement requirement) +54
       System.ServiceModel.Security.ServiceCredentialsSecurityTokenManager.CreateTlsnegoServerX509TokenProvider(RecipientServiceModelSecurityTokenRequirement recipientRequirement) +140
       System.ServiceModel.Security.ServiceCredentialsSecurityTokenManager.CreateTlsnegoSecurityTokenAuthenticator(RecipientServiceModelSecurityTokenRequirement recipientRequirement, Boolean requireClientCertificate, SecurityTokenResolver& sctResolver) +466
       System.ServiceModel.Security.ServiceCredentialsSecurityTokenManager.CreateSecurityTokenAuthenticator(SecurityTokenRequirement tokenRequirement, SecurityTokenResolver& outOfBandTokenResolver) +619
       System.ServiceModel.Security.SessionRenewSecurityTokenManager.CreateSecurityTokenAuthenticator(SecurityTokenRequirement tokenRequirement, SecurityTokenResolver& outOfBandTokenResolver) +85
       System.ServiceModel.Security.SymmetricSecurityProtocolFactory.OnOpen(TimeSpan timeout) +11294551
       System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan timeout) +21
       System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +261
       System.ServiceModel.Security.SecurityProtocolFactory.Open(Boolean actAsInitiator, TimeSpan timeout) +23
       System.ServiceModel.Security.SecurityListenerSettingsLifetimeManager.Open(TimeSpan timeout) +80
       System.ServiceModel.Channels.SecurityChannelListener`1.OnOpen(TimeSpan timeout) +204
       System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +261
       System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan timeout) +72
       System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +261
       System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout) +107
       System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +261
       System.ServiceModel.Security.SecuritySessionSecurityTokenAuthenticator.OnOpen(TimeSpan timeout) +129
       System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan timeout) +21
       System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +261
       System.ServiceModel.Security.CommunicationObjectSecurityTokenAuthenticator.Open(TimeSpan timeout) +20
       System.ServiceModel.Security.SecurityUtils.OpenTokenAuthenticatorIfRequired(SecurityTokenAuthenticator tokenAuthenticator, TimeSpan timeout) +34
       System.ServiceModel.Security.SecuritySessionServerSettings.OnOpen(TimeSpan timeout) +664
       System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan timeout) +21
       System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +261
       System.ServiceModel.Security.SecurityListenerSettingsLifetimeManager.Open(TimeSpan timeout) +133
       System.ServiceModel.Channels.SecurityChannelListener`1.OnOpen(TimeSpan timeout) +204
       System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +261
       System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan timeout) +72
       System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +261
       System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout) +107
       System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +261
       System.ServiceModel.HostingManager.ActivateService(String normalizedVirtualPath) +121
       System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath) +479
    
    [ServiceActivationException: The service '/Hello.svc' cannot be activated due to an exception during compilation.  The exception message is: The certificate 'CN=client.service.jinri.web' must have a private key that is capable of key exchange. The process must have access rights for the private key..]
       System.ServiceModel.AsyncResult.End(IAsyncResult result) +11527290
       System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +194
       System.ServiceModel.Activation.HostedHttpRequestAsyncResult.ExecuteSynchronous(HttpApplication context, Boolean flowContext) +176
       System.ServiceModel.Activation.HttpModule.ProcessRequest(Object sender, EventArgs e) +278
       System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +68
       System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
    

    2008年12月26日 5:20

答案

  • 你打开本地的终端服务进程试验一下。或许是因为这个原因导致的
    :运行--services.svc----terminal service,启动即可
    然后在f5 debug一下程序看看可以调试不~


    you have a dream,you gonna protect it!
    2009年5月16日 6:09
    版主

全部回复

  • 本地部署在IIS后,加了个主机头,然后打开网页service.client.web/MySimpleService.svc 就提示"句柄无效",如果我把认证去掉则没这个问题发生!~ 会不会是因为证书的原因呢????,
      <serviceCredentials>
          <serviceCertificate findValue="localhost" x509FindType="FindBySubjectName" storeLocation="LocalMachine" storeName="My"/>
          <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="ServerWcfService.CustomValidators.MyCustomValidator,ServerWcfService"/>
         </serviceCredentials>

    有谁知道怎么回事呢?

    2008年12月26日 7:26
  •  如果你只是自己做着玩的话,你将security设置为none 便可以了,

    看你现在的设置,是将security设置为需要证明书的认证安全等级了,这样的话,你参考一下
    http://msdn.microsoft.com/zh-cn/library/ms731925.aspx
    2009年2月1日 1:05
  • 你打开本地的终端服务进程试验一下。或许是因为这个原因导致的
    :运行--services.svc----terminal service,启动即可
    然后在f5 debug一下程序看看可以调试不~


    you have a dream,you gonna protect it!
    2009年5月16日 6:09
    版主