解析Silverlight调用WCF/Rest异常的解决方法
发布时间:2021-08-19 07:41:37
新建Rest服务接口:
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData(int value);
}
接着新建一个服务实现类:
public class Service1 : IService1
{
public string GetData(int value)
{
int i = 0;
int j = 5 / i;
return string.Format("You entered: {0}", value);
}
}
在这里让Service1 抛出”divided by zero exception:”
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="ServiceBehavior" name="WcfService1.Service1">
</service>
</services>
</system.serviceModel>
在这里注意<serviceDebug includeExceptionDetailInFaults="true" />
在Silverlight 客户端添加服务引用,名称为:ServiceReference1.
在页面上添加一个按钮,按钮的Click事件代码如下:
private void Button_Click(object sender, RoutedEventArgs e)
{
Service1Client client = new ServiceReference1.Service1Client();
client.GetDataCompleted += new EventHandler<GetDataCompletedEventArgs>(client_GetDataCompleted);
client.GetDataAsync(35); //Try GetData
}
void client_GetDataCompleted(object sender, ServiceReference1.GetDataCompletedEventArgs e)
{
}
运行,结果如下:
可以看到实际的异常是“尝试除以0”,但是由于浏览器限制,所有的异常都是NotFound。
在msdn上有两种方法可以解决这个问题,
最简单的就是在App.xaml.cs代码里面使用RegisterPrefix来使用备用客户端 HTTP 堆栈
public App()
{
bool bRegisterPrefix = WebRequest.RegisterPrefix(http://localhost:9541/,
WebRequestCreator.ClientHttp);
//other Code
}
再次运行代码:
这是SL调用WCF服务如何处理异常的方式,那么调用Rest服务呢?
首先要修改Web.config 节点下的serviceModel以让它支持Rest。
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="EndpointBehavior">
<webHttp helpEnabled="true" defaultOutgoingResponseFormat="Json"
faultExceptionEnabled="true" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="ServiceBehavior" name="WcfService1.Service1">
<endpoint behaviorConfiguration="EndpointBehavior" binding="webHttpBinding"
bindingConfiguration="" name="Rest" contract="WcfService1.IService1" />
</service>
</services>
</system.serviceModel>
在这里要设置webHttp 节点的faultExceptionEnabled=true.并且设置serviceDebug 的includeExceptionDetailInFaults 为true。
OK,服务的Web.config文件已经配置完毕了,接下来要为GetData方法添加WebGet特性修饰了。
public class Service1 : IService1
{
[WebGet()]
public string GetData(int value)
{
int i = 0;
int j = 5 / i;
return string.Format("You entered: {0}", value);
}
}
运行:
地址为:http://localhost:9541/Service1.svc/help
接着输入地址:http://localhost:9541/Service1.svc/GetData?value=3
可以看到得到了异常信息了。
注意:别忘记了添加跨域和授权文件:crossdomain.xml 和 clientaccesspolicy.xml 到网站根目录。
同样,修改SL客户端页面,添加一个Button,button的代码事件为:
private void btnRest_Click(object sender, RoutedEventArgs e)
{
WebClient wc = new WebClient();
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(
wc_DownloadStringCompleted);
wc.DownloadStringAsync(new Uri("http://localhost:9541/Service1.svc/GetData?value=3"));
}
void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
throw e.Error;
}
}
运行,点击btnRest
可以看到,Rest 调用的结果仍然是NotFound。
提示让我们查看Response属性和Status属性。
就看看Respone属性的ResponseStrem是什么吧。
可以看到errorMessage 就是返回的错误,很明显,我们需要对它反序列化成Exception的对象。
首先尝试使用DataContractSerializer来反序列化为FaultException类
因为我们尝试反序列化为FaultException类,但是XML数据的Element名称为Fault。所以失败,难道是有Fault类 ?可是找了很久也没发现Fault类。
但是在ReadObject方法中发现了一个verifyObjectName的重载。
将代码修改为:
DataContractSerializer serializer = new DataContractSerializer(
typeof(FaultException));
//object deserializerObject = serializer.ReadObject(errorStream);
object deserializerObject = serializer.ReadObject(XmlReader.Create(errorStream),false);
重新运行:
可以发现虽然序列化是成功的,但是序列化后的值全部是错误的。
最后没办法既然有XML的异常数据,那么可以尝试解析xml数据并使用自定义异常。
首先新建SLFaultException 类,继承Exception:代码如下:
public class SLFaultException : Exception
{
public ExceptionDetail Detail { get; set; }
public SLFaultException() { }
public SLFaultException(string message) : base(message) { }
public SLFaultException(string message, ExceptionDetail detail)
: base(message)
{
Detail = detail;
}
}
完整的代码如下:
void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
if (e.Error is WebException)
{
WebResponse errorResponse = ((WebException)e.Error).Response;
Stream errorStream = errorResponse.GetResponseStream();
XElement rootElement = XElement.Load(errorStream);
XElement detailElement = rootElement
.Descendants()
.First(el => el.Name.LocalName == "ExceptionDetail");
DataContractSerializer serializer = new DataContractSerializer(
typeof(ExceptionDetail));
ExceptionDetail exceptionDetail = (ExceptionDetail)serializer.ReadObject(
detailElement.CreateReader(), true);
SLFaultException faultException = new SLFaultException(
exceptionDetail.Message, exceptionDetail);
throw faultException;
}
}
}
虽然序列化为FaultException是失败的,但是xml节点的ExceptionDetail是可以被反序列回来的,当然上面的处理WebException的过程是可以被封装的,读者自己尝试下吧,呵呵。
结果如下图:
猜你喜欢
- 通过程序自动的读取其它网站网页显示的信息,类似于爬虫程序。比方说我们有一个系统,要提取BaiDu网站上歌曲搜索排名。分析系统在根据得到的数据
- 在Unity3d中开发虚拟摇杆方式有比较多,可以使用EasyTouch、FairyGUI等插件来开发。本文给大家介绍使用Unity3d的原生
- 一、实验题目二、分析实验要求为:实现一个界面,界面中包含一个文本显示区和两个按钮(存档和读档)读档按钮作用是打开文件并读取内容,将内容显示在
- feignclient https接口调用报证书错误问题最近在使用 feignclient 过程中,和第三方通过https 协议交互的时候,
- Spring Boot+Vue 前后端分离项目架构项目流程:1. SpringBoot 后端项目1、新建一个 SpringBoot 工程,并
- Java语言是一种半编译半解释的语言。Java的用户程
- 什么是Etcd?etcd是一个强大的一致性的分布式键值存储,它提供了一种可靠的方式来存储需要由分布式系统或机器群访问的数据。它优雅地处理网络
- using System; using System.Collections; using System.Text; using Syste
- java try catch异常后还会继续执行吗catch中如果你没有再抛出异常,那么catch之后的代码是可以继续执行的,但是try中,报
- Maven工程pom定义jdk版本今天把之前做的项目导进eclipse,然后发现报错,一些类在1.6中不支持,需要将JDK版本设置为1.7,
- classpath读取resources目录下文件最近在springboot+maven的项目中去读取资源文件的时候,报了找不到文件的错误。
- 目标:查询数据库中的字段,然后转换成 JSON 格式的数据,返回前台。环境:idea 2016.3.4, jdk 1.8, mysql 5.
- jasperreport导出的pdf每页显示的记录太少主要是确保Details的高度与Details中Field Text的高度一致。jas
- 基类:using System;using System.Collections.Generic;using System.Linq;usi
- 本文实例为大家分享了C#实现猜数字小游戏的具体代码,供大家参考,具体内容如下效果如图:代码:using System;using Syste
- 在java中调用xls格式化xml 使用javax.xml.transform.Transformer,将xml用xls格式化为另一种xml
- 最近在研究断点下载(下载续传)的功能,此功能需要服务端和客户端进行对接编写,本篇也是记录一下关于贴上关于实现服务端(Spring Boot)
- 本文所述实例实现将一张图片上传到指定的文件夹,然后在窗体上的PictrueBox控件中显示出来。具体功能代码如下:private void
- java类的方法,我特别喜欢《java编程思想》里面的描述,这本书说java类之间的相互通信是通过消息。比如顾客类的对象调用一个eat方法,
- 什么是POM?POM是项目对象模型(Project Object Model)的简称,它是Maven项目中的文件,使用XML表示,名称叫做p