我原来对请求的验证时,在OperationBehavior中写一个Check方法,把错误消息封装到Response的Message中返回客户端。但感觉不能重用。比如,很多方法都有参数sign,我要验证sign不为空,我就对每个Operation的检查里写判断。如果能像mvc3里面那样用特性来做验证会很好,省了很多事。幸好wcf也可以这样。
需要实现一个特性类,让operation方法调用之前做验证。代码如下:
public class BaseInspector : Attribute, IParameterInspector, IOperationBehavior
{
public virtual object BeforeCall(string operationName, object[] inputs)
{
return null;
}
public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
{ }
public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
{
}
public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
{
dispatchOperation.ParameterInspectors.Add(this);
}
public void Validate(OperationDescription operationDescription)
{
}
}
public class SignInspector : BaseInspector
{
public override object BeforeCall(string operationName, object[] inputs)
{
string sign = string.Empty;
if (inputs != null && inputs.Length > 0)
{
sign = inputs[1] as string;
}
if (!string.IsNullOrEmpty(sign))
{
throw new FaultException<FaultMessage>(new FaultMessage(ErrorInfo.AUTHENTICATION_FAILED), "invalid sign.");
}
return null;
}
}
然后在方法上面加这个特性就行
[SignInspector]
public Response QueryBalance(Request request, string sSign)
{
在客户端去捕获FaultException<T>就可以获得错误消息了,非常方便。
参考:
http://cgeers.com/2008/11/09/wcf-extensibility-parameter-inspectors/
http://stackoverflow.com/questions/1812187/wcf-parameter-validation-with-interceptor
http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.iparameterinspector.beforecall(v=vs.90).aspx