如果我们需要发送失败/成功结果,Wcf服务的最佳实践是什么?
例如:我们有Wcf服务,我们有一些服务BussinesLogic.我们的服务有一个运营合同:
[OperationContract]
/*SomeResult*/ SendImages(Bitmap[] images);
可能的情况:
BussinesLogic处于"糟糕"状态.逻辑处于错误状态,我们不知道什么时候可以再次工作.我该定制fault吗?在哪?我应该使用通用fault吗?我应该做enum OperationResult?或者maby,如果成功,任何结果都像是矫枉过正?可能的情景数量将保持不变.
我喜欢用这种方法:
[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; }
}
Run Code Online (Sandbox Code Playgroud)
我还有一些扩展:
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;
}
Run Code Online (Sandbox Code Playgroud)
扩展可以使用一行代码返回错误:
return retValue.WithError(ErrorCodes.RequestError);
Run Code Online (Sandbox Code Playgroud)
从我的wcf服务我永远不会抛出异常.
对不起代码墙
来电者的代码是这样的.但这一切都取决于您的要求
OperationResult res = _service.Register(username, password);
if(!res.Success)
{
if(res.Errors.Any(x => ErrorCodes.UsernameTaken)
{
// show error for taken username
}
...
}
Run Code Online (Sandbox Code Playgroud)