无法在我的客户端应用中捕获 WCF FaultException

Can't catch WCF FaultException in my client app

提问人:user9737577 提问时间:10/18/2023 最后编辑:marc_suser9737577 更新时间:10/18/2023 访问量:32

问:

我有我的 WCF 服务,我在其中定义了一个操作并实现了它。在这种方法中,我抛出一个.FaultException

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession, IncludeExceptionDetailInFaults = true)]
public class AQI : IAQI
{
    public void ControlModule(string moduleId, bool turnOn)
    {
        throw new FaultException("test error.");
    }
}

在我的文件中,我有以下代码:IService

[ServiceContract(SessionMode = SessionMode.Required)]
public interface IAQI
{
    [OperationContract(IsOneWay = true)]
    void ControlModule(string moduleId, bool turnOn);
}

然后,我有了我的客户端应用,这是一个控制台应用。在这个应用程序中,我使用以下代码创建了一个类:

public class AQIClass
{
     private AQIClient client;

     public AQIClass()
     {
         client = new AQIClient( new System.ServiceModel.WSHttpBinding(), new System.ServiceModel.EndpointAddress("http://localhost:64827/Service1.svc?singleWsdl") );
         client.Open();

         Console.WriteLine("Povezava je bila uspešno vzpostavljena.");
     }
   
     public async Task KrmiliModule(string sensorId, bool stanje)
     {
        try
        {
            await client.ControlModuleAsync(sensorId, stanje);
        }
        catch (TimeoutException t)
        {
            Console.WriteLine("TimeoutException");
            client.Abort();
        }
        catch (FaultException<ErrorInSettings> fesh)
        {
            Console.WriteLine(fesh.Detail.message);
            client.Abort();
        }
        catch (FaultException fe)
        {
            Console.WriteLine("FaultException");
            client.Abort();
        }
        catch (CommunicationException ce)
        {
            Console.WriteLine("CommunicationException");
            Console.WriteLine(ce.Message);
            client.Abort();
        }

        Console.WriteLine("Stanje modula je bilo uspešno spremenjeno.");
        Console.WriteLine();
    }
    
    public void CloseConnection()
    {
        client.Close();
    }

    public void AbortConnection()
    {
        client.Abort();
    }
}

我在我的主程序中使用这个类,代码如下:

AQIClass aqi = new AQIClass();
aqi.KrmiliModule("1", false);

我使用绑定。wsHttpBinding

当我在调试模式下启动 WCF 时,我可以看到抛出了一个错误,但它没有在我的客户端代码的 try-catch 语句中被捕获。

C# WCF

评论

0赞 Stephen Cleary 10/18/2023
你试过抓吗?Exception
0赞 user9737577 10/18/2023
如果抛出异常的方法无效,则它不会捕获它,否则它会捕获它
1赞 Selvin 10/18/2023
那是因为IsOneWay = true
0赞 Jiayao 10/18/2023
您可以命中断点或输出,以查看运行时在何处引发异常。

答: 暂无答案