c# - wcf服务运行结果的良好实践

标签 c# .net wcf

如果我们需要发送失败/成功结果,Wcf 服务的最佳实践是什么?

例如: 我们有 Wcf 服务,在服务后面我们有一些 BussinesLogic。 我们的服务有一个操作契约(Contract):

[操作合约] /*SomeResult*/SendImages(Bitmap[] images);

可能的场景:

  1. 操作完成,一切顺利。
  2. 位图参数不正确(位图的大小或数量错误)。
  3. BussinesLogic 处于“错误”状态。逻辑处于错误状态,我们 不知道什么时候可以再次工作。

我应该自定义 fault 吗?在什么情况下?我应该使用通用的 fault 吗?我应该制作 enum OperationResult 吗?或者,如果成功,任何结果都像是矫枉过正? 可能的场景数量将保持不变。

最佳答案

我喜欢使用这种方法:

[DataContract]
public class OperationResult
{
  public OperationResult()
  {
    Errors = new List<OperationError>();
    Success = true;
  }

  [DataMember]
  public bool Success { get; set; }

  [DataMember]
  public IList<OperationError> Errors { get; set; }
}

[DataContract(Name = "OperationResultOf{0}")]
public class OperationResult<T> : OperationResult
{
  [DataMember]
  public T Result { get; set; }
}

[DataContract]
public class OperationError
{
  [DataMember]
  public string ErrorCode { get; set; }

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

我还有一些扩展:

  public static OperationResult WithError(this OperationResult operationResult, string errorCode,
                                          string error = null)
  {
    return operationResult.AddErrorImpl(errorCode, error);
  }

  public static OperationResult<T> WithError<T>(this OperationResult<T> operationResult, string errorCode,
                                                string error = null)
  {
    return (OperationResult<T>) operationResult.AddErrorImpl(errorCode, error);
  }

  private static OperationResult AddErrorImpl(this OperationResult operationResult, string errorCode,
                                              string error = null)
  {
    var operationError = new OperationError {Error = error ?? string.Empty, ErrorCode = errorCode};

    operationResult.Errors.Add(operationError);
    operationResult.Success = false;

    return operationResult;
  }

  public static OperationResult<T> WithResult<T>(this OperationResult<T> operationResult, T result)
  {
    operationResult.Result = result;
    return operationResult;
  }

这些扩展使得用一行代码返回错误成为可能:

return retValue.WithError(ErrorCodes.RequestError);

在我的 wcf 服务中,我从未抛出异常。

对不起代码墙


来电者的代码是这样的。但这完全取决于您的要求

OperationResult res = _service.Register(username, password);

if(!res.Success)
{
    if(res.Errors.Any(x => ErrorCodes.UsernameTaken)
    {
       // show error for taken username
    }
    ...
}

关于c# - wcf服务运行结果的良好实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23537024/

相关文章:

.net - 在 IIS 中添加 net.pipe 绑定(bind)时出现 "Object reference not set"

c# - 我如何检测当前系统是什么语言

c# - 托管在 Windows 服务中的 WCF 服务 - 错误/预期的命名空间

c# - 来自 native 应用程序的 CoCreateInstance C# COM 组件找不到引用

.net - 显示属性 : No good for resources in App_GlobalResources

c# - .NET 中的 ManualResetEvent 和 AutoResetEvent 有什么区别?

c# - 有什么方法可以为未使用的使用生成编译器警告?

wcf - 在 IIS 上托管 WCF 服务(找不到资源)

c# - 阿塔塔。 C#。如何打开新标签页?

c# - 访问 ASP ListView 中的每个元素