为 WCF 服务提供失败状态

Providing failure status for WCF service

我有一个 WCF 服务,我通过以下方式调用它:

MyService client = new MyService();
bool result = client.MyServiceMethod(param1, param2);

变量结果设置为真或假以指示成功或失败。如果成功,则很明显,但如果失败,我需要获得有关失败原因的一些详细信息。

我使用的服务

OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
response.StatusCode = HttpStatusCode.BadRequest;
response.StatusDescription = "Invalid parameter.";
return false;

我的问题是如何检索响应描述,这是提供失败反馈的正确方法吗?

通常您使用 SOAP MSDN:Faults. Special advantage of faults is that WCF will ensure that your channel stays open after receiving fault message. By default, the service does not send any information explaining what happened. WCF does not reveal details about what the service does internally. See MSDN:Specifying and Handling Faults in Contracts and Services for more details. Also see SO:What exception type should be thrown with a WCF Service?

将问题传达给客户

出于调试目的,您可以添加 ServiceDebug 行为并将 IncludeExceptionDetailInFaults 设置为 true 以获取堆栈跟踪(在非生产环境中)

IMO 最好定义一个自定义 class,然后从您的方法中 return。此 class 将包含任何错误的详细信息。您可以使用 DataContracts 执行此操作。

一个简化的例子可能是这样的...

[ServiceContract]
public interface IMyContract
{
    [OperationContract]
    MyResult DoSomething();
}

[DataContract]
public class MyResult
{
    [DataMember]
    public bool IsSuccess { get; set; }

    [DataMember]
    public string ErrorDetails { get; set; }
}


public class MyService : IMyContract
{
    public MyResult DoSomething()
    {
        try
        {
            return new MyResult { IsSuccess = true };
        }
        catch
        {
            return new MyResult { IsSuccess = false, ErrorDetails = "Bad things" };
        }
    }
}

编辑:包括每个评论的消费代码。

var client = new MyService();
var results = client.DoSomething();

if (results.IsSuccess)
{
    Console.WriteLine("It worked");
}
else
{
    Console.WriteLine($"Oops: {results.ErrorDetails}");
}