3

您好,我已经尝试让 Ierrorhandler 工作了几个小时,但我非常卡住:) 我从本指南中获得了最多的结果

http://www.remondo.net/wcf-global-exception-handling-attribute-and-ierrorhandler/#comment-10385

但我无法让它与我的操作/功能一起使用

程序.cs

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

namespace Phpwcfconsole
{
    class program
    {
        static void Main(string[] args)
        {
            using (ServiceHost host = new ServiceHost(typeof(Service1)))
            {
                try
                {
                    host.Open();
                    Console.WriteLine("Host open. Press any key to <EXIT>");
                    Console.ReadLine();
                    host.Close();
                }
                catch (Exception e)
                {
                    Console.WriteLine(Environment.NewLine + e.Message);
                    host.Close(); 
                }
            }
        }
    }
}

应用程序配置

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <system.web>
  <compilation debug="true" />
 </system.web>

 <system.serviceModel>
  <services>
   <service behaviorConfiguration="Phpwcfconsole.Service1Behavior" 
        name="Phpwcfconsole.Service1">
    <endpoint 
      address="" 
      binding="basicHttpBinding" 
      contract="Phpwcfconsole.IService">
      <identity>
        <dns value="localhost" />
      </identity>
    </endpoint>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
    <host>
      <baseAddresses>
        <add baseAddress="http://agent007:8732/phpwcf/" />
      </baseAddresses>
    </host>
  </service>
</services>
<behaviors>
  <serviceBehaviors>
       <behavior name="Phpwcfconsole.Service1Behavior">
           <serviceMetadata httpGetEnabled="True"/>
           <serviceDebug includeExceptionDetailInFaults="false" />
         </behavior>
       </serviceBehaviors>
     </behaviors>
     <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
     <bindings>
       <basicHttpBinding>
         <binding name="MyServiceBinding"
                hostNameComparisonMode="StrongWildcard"
                receiveTimeout="00:10:00"
                sendTimeout="00:10:00"
                openTimeout="00:10:00"
                closeTimeout="00:10:00"
                maxReceivedMessageSize="20000000"
                maxBufferSize="20000000"
                maxBufferPoolSize="20000000"
                transferMode="Buffered"
                messageEncoding="Text"
                textEncoding="utf-8"
                bypassProxyOnLocal="false"
                useDefaultWebProxy="true" >
           <security mode="None" />
         </binding>
       </basicHttpBinding>
     </bindings>
   </system.serviceModel>
 </configuration>

IService.cs

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


namespace Phpwcfconsole
{
    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        string GetData(int value);
    }
}

服务器函数.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Phpwcfconsole
{
    public partial class Service1 : IService
    {
        public string GetData(int value)
        {
            throw new Exception("error");
        }
    }
}

异常处理程序.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Description;
using System.Collections.ObjectModel;
using System.ServiceModel.Configuration;

namespace Phpwcfconsole
{
    public class GlobalExceptionHandler : IErrorHandler
    {
        public bool HandleError(Exception ex)
        {
            return true;
        }

        public void ProvideFault(Exception ex, MessageVersion version,
                             ref Message msg)
        {
            // Do some logging here

            var newEx = new FaultException(
                string.Format("CALLED FROM YOUR GLOBAL EXCEPTION HANDLER BY {0}",
                              ex.TargetSite.Name));

            MessageFault msgFault = newEx.CreateMessageFault();
            msg = Message.CreateMessage(version, msgFault, newEx.Action);
        }
    }

    public class GlobalExceptionHandlerBehaviourAttribute : Attribute, IServiceBehavior
    {
        private readonly Type _errorHandlerType;

        public GlobalExceptionHandlerBehaviourAttribute(Type errorHandlerType)
        {
            _errorHandlerType = errorHandlerType;
        }

        public void Validate(ServiceDescription description, ServiceHostBase     serviceHostBase)
        {

        }

        public void AddBindingParameters(ServiceDescription description, ServiceHostBase serviceHostBase,
            Collection<ServiceEndpoint> endpoints, BindingParameterCollection parameters)
        {
        }

        public void ApplyDispatchBehavior(ServiceDescription description, ServiceHostBase serviceHostBase)
        {
            var handler = (IErrorHandler)Activator.CreateInstance(_errorHandlerType);

            foreach (ChannelDispatcherBase dispatcherBase in serviceHostBase.ChannelDispatchers)
            {
                var channelDispatcher = dispatcherBase as ChannelDispatcher;
                if (channelDispatcher != null)
                channelDispatcher.ErrorHandlers.Add(handler);
            }
        }
    }
}

好的,如果我在里面放一些 console.writeLine

公共类 GlobalExceptionHandlerBehaviourAttribute :属性,IServiceBehavior 函数我看到它们在我启动程序时运行。但我无法获得指南上的示例,该示例使用我的函数抛出异常并让我的 IErrorhandler 捕获该异常。

我在其他函数中尝试了一些异常,但我的 IErrorhandler 没有任何反应。

但是到目前为止我发现了一个异常,当我在Wcftestclient中添加我的服务然后停止调试并删除IService.cs中的[OperationContract]然后重新开始并尝试在不刷新的情况下运行该函数时,该异常得到被 IErrorhandler 捕获

所以我的问题是为什么我不能在函数中捕获异常?非常感谢您的回答。C(:

4

1 回答 1

0

FaultContractAttribute 是否足以满足您的要求?查看 msdn 文档中的示例。 http://msdn.microsoft.com/en-us/library/system.servicemodel.faultcontractattribute.aspx 这听起来与您尝试做的类似,比自定义服务行为更复杂。

在跨进程/机器使用 WCF 时,FaultContracts 等同于异常,因为消费者不一定是 .net 客户端。

于 2013-09-27T05:12:53.627 回答