WCF服务的异常消息

简介:

WCF Service发生异常的时候,客户端一般只能看见这样一个错误:“The server encountered an error processing the request”,而异常的类型和引起异常的代码都没有显示,究其原因是出于安全考虑。如果想要暴露这些异常信息的细节给客户端,只需要在服务器的配置文件上修改<serviceDebug includeExceptionDetailInFaults="true" />。

(一)SOAP WCF Service的异常

(1) 当serviceDebug includeExceptionDetailInFaults="false"

 

IDemoService.cs:

 

复制代码
using System.ServiceModel;

namespace WCFDemo
{    
    [ServiceContract(Name = "IDemoService")]
    public interface IDemoService
    {
        [OperationContract]
        int Divide(int numerator, int denominator);
    }
}
复制代码

 

DemoService.cs:

 

复制代码
using System;
using System.ServiceModel.Activation;

namespace WCFDemo
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class DemoService : IDemoService
    {
        public int Divide(int numerator, int denominator)
        {
            return numerator / denominator;
        }
    }
}
复制代码

 

 

web.config

 

复制代码
<?xml version="1.0"?> 
<configuration> 
    <system.web> 
      <compilation targetFramework="4.0" /> 
    </system.web>

    <system.serviceModel> 
      <services> 
        <service name="WCFDemo.DemoService" behaviorConfiguration="metaBehavior"> 
          <endpoint address="DemoService" binding="basicHttpBinding" contract="WCFDemo.IDemoService" /> 
          <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint> 
          <host> 
            <baseAddresses> 
              <add baseAddress="http://localhost:8080"/> 
            </baseAddresses> 
          </host> 
        </service> 
      </services> 
        <behaviors> 
            <serviceBehaviors> 
                <behavior name="metaBehavior"> 
                    <serviceMetadata httpGetEnabled="true" /> 
                    <serviceDebug includeExceptionDetailInFaults="false" /> 
                </behavior> 
            </serviceBehaviors> 
        </behaviors> 
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> 
    </system.serviceModel> 
</configuration>
复制代码

 

 

建立一个Windows Client,Form1.cs:

 

复制代码
private void buttonCalculate_Click(object sender, EventArgs e) 
{ 
    DemoServiceReference.DemoServiceClient demoServiceClient = new DemoServiceReference.DemoServiceClient(); 
    textBoxResult.Text = demoServiceClient.Divide(Convert.ToInt32(textBoxNumerator.Text), Convert.ToInt32(textBoxDenominator.Text)).ToString(); 
} 
复制代码

 

 

Client app.config

 

复制代码
<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <system.serviceModel> 
        <bindings> 
            <basicHttpBinding> 
                <binding name="BasicHttpBinding_IDemoService" /> 
            </basicHttpBinding> 
        </bindings> 
        <client> 
            <endpoint address="http://169.254.14.147:8080/DemoService.svc/DemoService" 
                binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IDemoService" 
                contract="DemoServiceReference.IDemoService" name="BasicHttpBinding_IDemoService" /> 
        </client> 
    </system.serviceModel> 
</configuration>
复制代码

 

 

在正常情况下的消息为:

image

 

image

 

Request Body:

复制代码
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <Divide xmlns="http://tempuri.org/">
      <numerator>100</numerator>
      <denominator>10</denominator>
    </Divide>
  </s:Body>
</s:Envelope>
复制代码

 

Response Body:

复制代码
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <DivideResponse xmlns="http://tempuri.org/">
      <DivideResult>10</DivideResult>
    </DivideResponse>
  </s:Body>
</s:Envelope>
复制代码

 

 

在发生异常时:

image

image

 

Request Header:

复制代码
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <Divide xmlns="http://tempuri.org/">
      <numerator>100</numerator>
      <denominator>0</denominator>
    </Divide>
  </s:Body>
</s:Envelope>
复制代码

 

Response Body:

复制代码
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <s:Fault>
      <faultcode xmlns:a="http://schemas.microsoft.com/net/2005/12/windowscommunicationfoundation/dispatcher">a:InternalServiceFault</faultcode>
      <faultstring xml:lang="en-US">The server was unable to process the request due to an internal error.  For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the &lt;serviceDebug&gt; configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework SDK documentation and inspect the server trace logs.</faultstring>
    </s:Fault>
  </s:Body>
</s:Envelope>
复制代码


 

(2)当serviceDebug includeExceptionDetailInFaults="true"

 

可以看到异常的消息为”Attempted to divide by zero.”

image

 

response body:

复制代码
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <s:Fault>
      <faultcode xmlns:a="http://schemas.microsoft.com/net/2005/12/windowscommunicationfoundation/dispatcher">a:InternalServiceFault</faultcode>
      <faultstring xml:lang="en-US">Attempted to divide by zero.</faultstring>
      <detail>
        <ExceptionDetail xmlns="http://schemas.datacontract.org/2004/07/System.ServiceModel" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
          <HelpLink i:nil="true"/>
          <InnerException i:nil="true"/>
          <Message>Attempted to divide by zero.</Message>
          <StackTrace>
            at WCFDemo.DemoService.Divide(Int32 numerator, Int32 denominator)&#xD;
            at SyncInvokeDivide(Object , Object[] , Object[] )&#xD;
            at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]&amp; outputs)&#xD;
            at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&amp; rpc)&#xD;
            at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&amp; rpc)&#xD;
            at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc&amp; rpc)&#xD;
            at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
          </StackTrace>
          <Type>System.DivideByZeroException</Type>
        </ExceptionDetail>
      </detail>
    </s:Fault>
  </s:Body>
</s:Envelope>
复制代码

 

 

(二)JSON WCF Service的异常

image

 

(1) serviceDebug includeExceptionDetailInFaults="false"

IDemoJsonService.cs:

 

复制代码
using System.ServiceModel;

namespace WCFDemo
{
    [ServiceContract(Namespace = "IDemoJsonService")]
    public interface IDemoJsonService
    {
        [OperationContract]
        int Divide(int numerator, int denominator);
    }
}
复制代码

 

DemoJsonService.cs

 

复制代码
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

namespace WCFDemo
{

    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class DemoJsonService : IDemoJsonService
    {
        [WebGet(UriTemplate="Divide?numerator={numerator}&denominator={denominator}", ResponseFormat=WebMessageFormat.Json)]
        public int Divide(int numerator, int denominator)
        {
            return numerator / denominator;
        }
    }
}
复制代码


 

web.config

 

复制代码
<?xml version="1.0"?> 
<configuration> 
    <system.web> 
      <compilation debug="true" targetFramework="4.0" /> 
    </system.web> 
    <system.serviceModel> 
      <services> 
        <service name="WCFDemo.DemoService" behaviorConfiguration="metaBehavior"> 
          <endpoint address="DemoService" binding="basicHttpBinding" contract="WCFDemo.IDemoService" />          
          <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint> 
        </service> 
        <service name="WCFDemo.DemoJsonService" behaviorConfiguration="metaBehavior"> 
          <endpoint address="DemoJsonService" binding="webHttpBinding" contract="WCFDemo.IDemoJsonService" behaviorConfiguration="WCFDemo.DemoJsonService.endpointBehavior" /> 
          <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint> 
        </service> 
      </services> 
        <behaviors> 
            <serviceBehaviors> 
                <behavior name="metaBehavior"> 
                    <serviceMetadata httpGetEnabled="true" /> 
                    <serviceDebug includeExceptionDetailInFaults="false" /> 
                </behavior> 
            </serviceBehaviors> 
          <endpointBehaviors> 
            <behavior name="WCFDemo.DemoJsonService.endpointBehavior"> 
              <webHttp helpEnabled="true"/> 
            </behavior> 
          </endpointBehaviors> 
        </behaviors> 
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> 
    </system.serviceModel> 
</configuration>
复制代码

 

 

正常情况下:

image

 

发生异常时:

 

image

复制代码
<?xml version="1.0" encoding="utf-8"?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
  <head> 
    <title>Request Error</title> 
    <style>BODY { color: #000000; background-color: white; font-family: Verdana; margin-left: 0px; margin-top: 0px; } #content { margin-left: 30px; font-size: .70em; padding-bottom: 2em; } A:link { color: #336699; font-weight: bold; text-decoration: underline; } A:visited { color: #6699cc; font-weight: bold; text-decoration: underline; } A:active { color: #336699; font-weight: bold; text-decoration: underline; } .heading1 { background-color: #003366; border-bottom: #336699 6px solid; color: #ffffff; font-family: Tahoma; font-size: 26px; font-weight: normal;margin: 0em 0em 10px -20px; padding-bottom: 8px; padding-left: 30px;padding-top: 16px;} pre { font-size:small; background-color: #e5e5cc; padding: 5px; font-family: Courier New; margin-top: 0px; border: 1px #f0f0e0 solid; white-space: pre-wrap; white-space: -pre-wrap; word-wrap: break-word; } table { border-collapse: collapse; border-spacing: 0px; font-family: Verdana;} table th { border-right: 2px white solid; border-bottom: 2px white solid; font-weight: bold; background-color: #cecf9c;} table td { border-right: 2px white solid; border-bottom: 2px white solid; background-color: #e5e5cc;}</style> 
  </head> 
  <body> 
    <div id="content"> 
      <p class="heading1">Request Error</p> 
      <p xmlns="">The server encountered an error processing the request. Please see the <a rel="help-page" href="http://169.254.14.147:8080/DemoJsonService.svc/DemoJsonService/help">service help page</a> for constructing valid requests to the service.</p> 
    </div> 
  </body> 
</html>
复制代码

 

(2)当serviceDebug includeExceptionDetailInFaults="true"

 

web.config

 

复制代码
<?xml version="1.0"?> 
<configuration> 
    <system.web> 
      <compilation debug="true" targetFramework="4.0" /> 
    </system.web> 
    <system.serviceModel> 
      <services> 
        <service name="WCFDemo.DemoService" behaviorConfiguration="metaBehavior"> 
          <endpoint address="DemoService" binding="basicHttpBinding" contract="WCFDemo.IDemoService" />          
          <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint> 
        </service> 
        <service name="WCFDemo.DemoJsonService" behaviorConfiguration="metaBehavior"> 
          <endpoint address="DemoJsonService" binding="webHttpBinding" contract="WCFDemo.IDemoJsonService" behaviorConfiguration="WCFDemo.DemoJsonService.endpointBehavior" /> 
          <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint> 
        </service> 
      </services> 
        <behaviors> 
            <serviceBehaviors> 
                <behavior name="metaBehavior"> 
                    <serviceMetadata httpGetEnabled="true" /> 
                    <serviceDebug includeExceptionDetailInFaults="true" /> 
                </behavior> 
            </serviceBehaviors> 
          <endpointBehaviors> 
            <behavior name="WCFDemo.DemoJsonService.endpointBehavior"> 
              <webHttp helpEnabled="true"/> 
            </behavior> 
          </endpointBehaviors> 
        </behaviors> 
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> 
    </system.serviceModel> 
</configuration> 
复制代码

 

image

 

复制代码
<?xml version="1.0" encoding="utf-8"?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
  <head> 
    <title>Request Error</title> 
    <style>BODY { color: #000000; background-color: white; font-family: Verdana; margin-left: 0px; margin-top: 0px; } #content { margin-left: 30px; font-size: .70em; padding-bottom: 2em; } A:link { color: #336699; font-weight: bold; text-decoration: underline; } A:visited { color: #6699cc; font-weight: bold; text-decoration: underline; } A:active { color: #336699; font-weight: bold; text-decoration: underline; } .heading1 { background-color: #003366; border-bottom: #336699 6px solid; color: #ffffff; font-family: Tahoma; font-size: 26px; font-weight: normal;margin: 0em 0em 10px -20px; padding-bottom: 8px; padding-left: 30px;padding-top: 16px;} pre { font-size:small; background-color: #e5e5cc; padding: 5px; font-family: Courier New; margin-top: 0px; border: 1px #f0f0e0 solid; white-space: pre-wrap; white-space: -pre-wrap; word-wrap: break-word; } table { border-collapse: collapse; border-spacing: 0px; font-family: Verdana;} table th { border-right: 2px white solid; border-bottom: 2px white solid; font-weight: bold; background-color: #cecf9c;} table td { border-right: 2px white solid; border-bottom: 2px white solid; background-color: #e5e5cc;}</style> 
  </head> 
  <body> 
    <div id="content"> 
      <p class="heading1">Request Error</p> 
      <p xmlns="">The server encountered an error processing the request. Please see the <a rel="help-page" href="http://169.254.14.147:8080/DemoJsonService.svc/DemoJsonService/help">service help page</a> for constructing valid requests to the service. The exception message is 'Attempted to divide by zero.'. See server logs for more details. The exception stack trace is: </p> 
      <p>   at WCFDemo.DemoJsonService.Divide(Int32 numerator, Int32 denominator) 
   at SyncInvokeDivide(Object , Object[] , Object[] ) 
   at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]&amp; outputs) 
   at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&amp; rpc) 
   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&amp; rpc) 
   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc&amp; rpc) 
   at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)</p> 
    </div> 
  </body> 
</html>
复制代码

 

 

(三)总结

出于安全考虑,WCF Server不会暴露异常的详细信息,如果想看到这一信息,需要在服务器上将配置文件修改为<serviceDebug includeExceptionDetailInFaults="true" />。











本文转自JF Zhu博客园博客,原文链接:   http://www.cnblogs.com/jfzhu/p/4055024.html ,如需转载请自行联系原作者





相关文章
|
9月前
|
前端开发
WCF更新服务引用报错的原因之一
WCF更新服务引用报错的原因之一
|
8月前
|
C# 数据安全/隐私保护
c#如何创建WCF服务到发布(SqlServer版已经验证)
c#如何创建WCF服务到发布(SqlServer版已经验证)
38 0
|
8月前
|
安全 数据库连接 数据库
WCF服务创建到发布(SqlServer版)
在本示例开始之前,让我们先来了解一下什么是wcf? wcf有哪些特点? wcf是一个面向服务编程的综合分层架构。该架构的项层为服务模型层。 使用户用最少的时间和精力建立自己的软件产品和外界通信的模型。它使得开发者能够建立一个跨平台的安全、可信赖、事务性的解决方案。且能与已有系统兼容写作。 简单概括就是:一组数据通信的应用程序开发接口。
57 0
Visual Studio 2022 创建 WCF服务 找不到
Visual Studio 2022 创建 WCF服务 找不到
|
C++
WCF基础教程(二)——解析iis8和iis8.5+VS2013发布wcf服务问题
WCF基础教程(二)——解析iis8和iis8.5+VS2013发布wcf服务问题
102 0
WCF基础教程(二)——解析iis8和iis8.5+VS2013发布wcf服务问题
WCF使用纯代码的方式进行服务寄宿
服务寄宿的目的是为了开启一个进程,为WCF服务提供一个运行的环境。通过为服务添加一个或者多个终结点,使之暴露给潜在的服务消费,服务消费者通过匹配的终结点对该服务进行调用,除去上面的两种寄宿方式,还可以以纯代码的方式实现服务的寄宿工作。
850 0
|
Windows
WCF服务寄宿到IIS
一.WCF简介: Windows Communication Foundation(WCF)是由微软开发的一系列支持数据通信的应用程序框架,可以翻译为Windows 通讯开发平台。整合了原有的windows通讯的 .net Remoting,WebService,Socket的机制,并融合有HTTP和FTP的相关技术。
1046 0
WCF服务自我寄宿
WCF服务的寄宿方式 WCF寄宿方式是一种非常灵活的操作,可以寄宿在各种进程之中,常见的寄宿有: IIS服务、Windows服务、Winform程序、控制台程序中进行寄宿,从而实现WCF服务的运行,为调用者方便、高效提供服务调用。
994 0
|
网络架构
(纯代码)快速创建wcf rest 服务
因为有一个小工具需要和其它的业务对接数据,所以就试一下看能不能弄一个无需配置快速对接的方法出来,百(以)度(讹)过(传)后(讹),最后还是对照wcf配置对象调试出来了: 1.创建WebHttpBinding 2.
979 0