c# WCF 捕获基本类型的故障异常 [英] c# WCF catch Fault Exceptions of Base type
问题描述
我一直在到处寻找如何在 c# 中捕获基本错误合同类型.我想让我所有的错误合约都继承自一个类,并在 MVC 控制器中有一个 catch(FaultException fex).
I have been looking everywhere to find out how to catch a base fault contract type in c#. I would like to have all my fault contracts inherit from one class and have one catch(FaultException fex) in the MVC controller.
数据合同
[DataContract]
public class BaseClass1
{ }
[DataContract]
public class Class2 : BaseClass1
{ }
服务
[ServiceContract]
public interface IService1
{
[OperationContract]
[FaultContract(typeof(BaseClass1))]
[FaultContract(typeof(Class2))] //Do I need this one?
void ThrowClass2();
}
public class Service1 : IService1
{
public void ThrowClass2()
{
throw new FaultException<Class2>(new Class2(), "Class2 Reason");
}
}
服务消费者
FaultTestService.Service1Client client = null;
try
{
client = new FaultTestService.Service1Client();
client.ThrowAmpFaults("InvalidParameter", 0);
}
catch (FaultException<Namespace.BaseClass1> fex)
{
//DOES NOT GO IN HERE AS I WOULD EXPECT
}
catch (FaultException fex)
{
//Other Possible Option
MessageFault fault = fex.CreateMessageFault();
var fe1 = fault.GetDetail<BaseClass1>();
//This throws a serialization exception it needs <Class2>
}
请让我知道是否可以修复这些 catch 语句中的任何一个来执行我正在寻找的操作.
Please let me know if either of these catch statements can be fixed to do what I am looking for.
推荐答案
该语法在 C# 中不起作用.请考虑以下解决方法".
That syntax will not work in C#. Consider the folowing "workaround" instead.
try
{
throw new FaultException<DerivedClass2>(new DerivedClass2());
}
catch (FaultException fex)
{
bool handled = false;
Type fexType = fex.GetType();
if (fexType.IsGenericType && fexType.GetGenericTypeDefinition() == typeof(FaultException<>))
{
if (typeof(BaseClass1).IsAssignableFrom(fexType.GetGenericArguments()[0]))
{
object detail = fexType.GetProperty("Detail").GetValue(fex, null);
// Use detail here.
handled = true;
}
}
if (!handled)
throw; // Don't know how to handle. Re-throw.
}
如果我们忽略 Detail == null
但构造的泛型类型匹配的异常情况,这可以简化.我还将使用 C# dynamic 关键字进一步简化它.
This can be simplified if we disregard the unusual case where Detail == null
but the constructed generic type matches. I'll also use the C# dynamic keyword to simplify it a little further.
try
{
throw new FaultException<DerivedClass2>(new DerivedClass2());
}
catch (FaultException fex)
{
bool handled = false;
Type fexType = fex.GetType();
if (fexType.IsGenericType && fexType.GetGenericTypeDefinition() == typeof(FaultException<>))
{
object detail = ((dynamic)fex).Detail;
if (detail is BaseClass1) // true for subclasses too!
{
// Use detail here.
}
}
if (!handled)
throw; // Don't know how to handle. Re-throw.
}
要考虑的另一件事是您是否应该只使用 throw new FaultException
.这种抛出方式可以让你使用你最初提供的代码来捕捉.
The other thing to consider is whether you should just use throw new FaultException<BaseClass1>(new DerivedClass2())
. This way of throwing will let you catch using the code you originally provided.
这篇关于c# WCF 捕获基本类型的故障异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!