WCF服务的异常消息

时间:2022-09-08 19:44:00

原创地址:http://www.cnblogs.com/jfzhu/p/4055024.html

转载请注明出处

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>

在正常情况下的消息为:

WCF服务的异常消息

WCF服务的异常消息

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>

在发生异常时:

WCF服务的异常消息

WCF服务的异常消息

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.”

WCF服务的异常消息

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)
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)
</StackTrace>
<Type>System.DivideByZeroException</Type>
</ExceptionDetail>
</detail>
</s:Fault>
</s:Body>
</s:Envelope>

(二)JSON WCF Service的异常

WCF服务的异常消息

(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>

正常情况下:

WCF服务的异常消息

发生异常时:

WCF服务的异常消息

<?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>

WCF服务的异常消息

<?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" />。

WCF服务的异常消息

WCF服务的异常消息的更多相关文章

  1. WCF 服务端异常封装

    通常WCF服务端异常的详细信息只有在调试环境下才暴露出来,但我目前有需求需要将一部分异常的详细信息传递到客户端,又需要保证一定的安全性. 最简单的办法当然是在服务端将异常捕获后,序列化传给客户端,但这 ...

  2. WCF分布式开发步步为赢&lpar;13&rpar;&colon;WCF服务离线操作与消息队列MSMQ

    之前曾经写过一个关于MSMQ消息队列的文章:WCF分布式开发必备知识(1):MSMQ消息队列 ,当时的目的也是用它来作为学习WCF 消息队列MSMQ编程的基础文章.在那篇文章里,我们详细介绍了MSMQ ...

  3. WCF&amp&semi;AppFabric :异常消息: 内存入口检查失败

    bug描述 发件人信息: System.ServiceModel.ServiceHostingEnvironment+HostingManager/31242459 异常: System.Servic ...

  4. wcf win7&plus;iis7 异常消息为&colon; 可能证书&OpenCurlyDoubleQuote;CN&equals;PmsWcfServer”没有能够进行密钥交换的私钥

    原因是证书没有用户权限,解决方法: 1.开始-运行-mmc 2.添加[证书]管理单元 3.选择[证书(本地计算机)]-[个人]-[证书],右击PmsWcfServer证书-[所有任务]-[管理密钥] ...

  5. WCF服务创建与抛出强类型SOAP Fault

    原创地址:http://www.cnblogs.com/jfzhu/p/4060666.html 转载请注明出处 前面的文章<WCF服务的异常消息>中介绍过,如果WCF Service发生 ...

  6. 服务端增加WCF服务全局异常处理机制

    服务端增加WCF服务全局异常处理机制,任一WCF服务或接口方式出现异常,将统一调用WCF_ExceptionHandler.ProvideFault方法,因此不需要每个方法使用try catch写法. ...

  7. WCF服务全局异常处理机制

    服务端增加WCF服务全局异常处理机制,任一WCF服务或接口方式出现异常,将统一调用WCF_ExceptionHandler.ProvideFault方法,因此不需要每个方法使用try catch写法. ...

  8. WCF服务全局统一异常处理机制

    转载:http://www.csframework.com/archive/1/arc-1-20150109-2193.htm 服务端增加WCF服务全局异常处理机制,任一WCF服务或接口方式出现异常, ...

  9. WCF服务上应用protobuf

    WCF服务上应用protobuf Web api  主要功能: 支持基于Http verb (GET, POST, PUT, DELETE)的CRUD (create, retrieve, updat ...

随机推荐

  1. opencv 小任务1 图片的缩放

    #include <opencv2/opencv.hpp> using namespace std; int main() { double fScale = 0.2; //缩放倍数 Cv ...

  2. 移动端自动化环境搭建-Robot Framework的安装

    A.安装依赖 RF框架,robotframework本身. B.安装过程 可以通过下载 exe 程序进行安装,Robot Framework 分别提供了,win-amd64.exe 和 win32.e ...

  3. js原生实现淡入淡出

         转自http://kb.cnblogs.com/page/90854/ 参数说明: fadeIn()与fadeOut()均有三个参数,第一个是事件, 必填; 第二个是淡入淡出速度, 正整数, ...

  4. NLog

    C# 使用NLog记录日志 C#第三方日志库Nlog NLog类库使用探索——详解配置 使用Nlog记录日志到数据库 NLog文章系列——系列文章目录以及简要介绍 NLog日志框架简写用法(write ...

  5. 对象导论 Thinking in Java 第一章

    1.1 抽象过程 1.人们能够解决问题的复杂性直接取决于抽象的类型和质量. 1.2 每个对象都有一个接口 1.3 每个对象都提供服务 1.4 被隐藏的具体实现 1.程序猿分为:类创建者 和 客户端程序 ...

  6. VS编译时自动下载NuGet管理的库

    之前一直使用NuGet来管理一些第三方的库,但是每次check in代码时候为了保证编译通过,都需要把对应的packages check in. 比较耗费时间,特别是往github上同步代码,而且这些 ...

  7. C&plus;&plus;与Lua交互(四)

    引言 通过前几篇,我们已经对Lua的C API有了一定的了解,如lua_push*.lua_is*.lua_to*等等.用C++调用Lua数据时,我们主要运用lua_getglobal与lua_pus ...

  8. HDU-4651 Partition 整数拆分&comma;递推

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4651 题意:求n的整数拆为Σ i 的个数. 一般的递归做法,或者生成函数做法肯定会超时的... 然后要 ...

  9. 关于oracle导出时的query用法

    QUERY参数后面跟的是where条件,值得注意的是,整个where子句需要使用""括起来,where子句的写法和SELECT中相同: 如果是UNIX平台所有"和'都需 ...

  10. 让asp&period;net网站支持多语言,使用资源文件

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs&quo ...