您的位置:首页 > 其它

WCF 学习笔记 (1) - Specify Fault Behaviors for the Service

2009-01-03 03:13 549 查看
本帖示范在 WCF 中,如何用 FaultContractAttribute 指定 SOAP 错误,并搭配泛型的 FaultException<自订类> 去封装自订的错误讯息,以回传给客户端。本帖提供 WCF + ASP.NET 3.5 的示例下载。

-------------------------------------------------
本帖的示例代码下载点:
http://files.cnblogs.com/WizardWu/090103.zip
(执行本示例,需要 Visual Studio 2008 + SP1,不需要数据库)
-------------------------------------------------

用 VS 2008 + SP1,双击 WcfServiceLibrary1.sln 打开 solution 后,直接按 F5 执行示例,可看到下图 1 的画面。当您在 TextBox 输入数字并按 Button 时,WCF Service 会用 int.Parse 方法,将输入的字符串转型成数字;当您输入的非数字时,就会在 WCF 中引发转型错误,接着会在 Service1.cs 中抛回一个 FaultException<TDetial>。

Default.aspx.cs
using System.ServiceModel;
using WcfServiceLibrary1;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}

protected void Button1_Click(object sender, EventArgs e)
{
this.transferWCF();
}

private void transferWCF()
{
ServiceReference1.Service1Client prox = new ServiceReference1.Service1Client();
int i = 0;

try
{
i = prox.GetData(TextBox1.Text);
Response.Write(i);
}
catch (FaultException<FaultInfo> fault)
{
Response.Write(fault.Detail.Reason);
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}

}

上方代码中的 Detail 属性,为 FaultException<TDetail> 泛型类所特有的属性,里然包含错误的详细信息,但旧式非泛型的 FaultException 类没有这个属性。

建置 solution 完成后,若您去浏览 WSDL,会发现里面有 fault contract 的相关信息。

-----------------------------------

参考书籍:

[1] Microsoft .NET Framework 3.5-Windows Communication Foundation, MCTS EXAM 70-503 Training Kit
http://www.microsoft.com/learning/en/us/Books/12486.aspx
http://www.amazon.com/MCTS-Self-Paced-Training-70-503-PRO-Certification/dp/0735625654

-----------------------------------

参考文件:

[2] MSDN Library

FaultContractAttribute 类:
http://msdn.microsoft.com/zh-cn/library/system.servicemodel.faultcontractattribute.aspx

FaultException<TDetail> 泛型类:
http://msdn.microsoft.com/zh-cn/library/ms576199.aspx

FaultException<TDetail>Detail 属性:
http://msdn.microsoft.com/zh-cn/library/ms575596.aspx

[3] WCF学习----我的第一个WCF程序
/article/4679093.html

-----------------------------------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐