WCF崩溃服务而不是向客户端发送自定义FAULT

时间:2014-04-09 11:16:49

标签: c# .net web-services wcf fault

我正在尝试实施故障响应。但到目前为止DEBUG mode它崩溃了服务而不是发送自定义错误。

这是我的代码:

IService1.cs

namespace WcfService1
{
    [ServiceContract]
    public interface IService1
    {

        [FaultContract(typeof(ErrorResponse))]
        [OperationContract]
        [WebGet(ResponseFormat = WebMessageFormat.Xml,
                UriTemplate = "/GetData?value={value}")]
        string GetData(int value);
    }
}

Service1.svc.cs

namespace WcfService1
{
    public class Service1 : IService1
    {
        public string GetData(int value)
        {
            if (value == 5)
                throw new FaultException<ErrorResponse>(new ErrorResponse("Message", "Exception"));
            return string.Format("You entered: {0}", value);
        }
    }
}

ErrorResponse.cs

namespace WcfService1
{
    [DataContract]
    public class ErrorResponse
    {
        public ErrorResponse(string message, string exType)
        {
            this.Message = message;
            this.ExceptionType = exType;
        }

        [DataMember]
        public string Message { get; set; }

        [DataMember]
        public string ExceptionType { get; set; }
    }
}

的Web.config

<?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <services>
      <service name="WcfService1.Service1"  
               behaviorConfiguration="Service1ServiceBehavior">
        <endpoint address=""
                  binding="webHttpBinding"
                  behaviorConfiguration="Service1EndpointBehavior"
                  contract="WcfService1.IService1">
        </endpoint>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="Service1ServiceBehavior">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="Service1EndpointBehavior">
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>

现在它应该在我用http://localhost:1151/Service1.svc/GetData?value=5调用它时发送XML,而不是它崩溃服务并在抛出行显示异常。

有什么建议吗?

0 个答案:

没有答案