WCF服务异常良好做法 [英] Wcf service exception good practices
本文介绍了WCF服务异常良好做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我开发分布式应用程序。在这里面,有我必须验证角色和权限集。结果
是一个很好的初步实践抛出的例外,每例如,未经授权的访问?结果
或我应该把一些信息返回给客户端?
I am developing a distributed application. In it, there are roles and sets of permissions that I must validate.
Is a good pratice to throw an exception, in per example, unauthorized access?
Or should I send some message back to the client?
推荐答案
在您的服务操作,你可以指定一个 FaultContract 的,这将有助于两个目的,像这样:
On your service operation, you can specify a FaultContract that will serve both purposes like so:
[OperationContract]
[FaultContract(typeof(MyServiceFault))]
void MyServiceOperation();
注意MyServiceFault必须标有DataContract和DataMember属性,以同样的方式将复杂类型
Note that MyServiceFault must be marked with DataContract and DataMember attributes, in the same way you would a complex type:
[DataContract]
public class MyServiceFault
{
private string _message;
public MyServiceFault(string message)
{
_message = message;
}
[DataMember]
public string Message { get { return _message; } set { _message = value; } }
}
在服务端,你就能够:
throw new FaultException<MyServiceFault>(new MyServiceFault("Unauthorized Access"));
和在客户端:
try
{
...
}
catch (FaultException<MyServiceFault> fault)
{
// fault.Detail.Message contains "Unauthorized Access"
}
这篇关于WCF服务异常良好做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文