我有一个WCF服务,并且所有操作都需要MyServiceRequest参数(或派生类型)
并返回MyServiceResponse(或派生的类型),即:
[OperationContract]
MySeviceResponse FindAppointments(FindAppointmentRequest request);
[OperationContract]
MyServiceResponse MakeAnAppointment(MakeAnAppointmentRequest request);
[OperationContract]
MyServiceResponse RegisterResource(RegisterResourceRequest request);
FindAppointmentRequest,MakeAnAppointmentRequest和RegisterResourceRequest扩展了MyServiceRequest,其中包含属性UserName和UserPassword。
如果请求中的UserName/UserPassword对不正确,则此方法均无法正确执行。
我想创建一个拦截器,它不仅检查给定的UserName/UserPassword对是否正确(使用IParameterInspector相当简单),而且还返回扩展MyServiceResponse的ErrorRespone类型的客户端对象。
IParameterInspector可以阻止服务执行请求的方法并立即返回ErrorResponse吗?
最佳答案
IParameterInspector可以通过引发异常来阻止执行操作。这是一个例子。
定义自定义故障契约(Contract):
public class DataAccessFaultContract
{
public string ErrorMessage { get; set; }
}
然后检查员:
public class InspectorAttribute : Attribute, IParameterInspector, IOperationBehavior
{
public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
{
}
public object BeforeCall(string operationName, object[] inputs)
{
MyServiceRequest request = null;
if (inputs != null && inputs.Length > 0)
{
request = inputs[0] as MyServiceRequest;
}
if (request != null && request.Username != "user" && request.Password != "secret")
{
var fc = new DataAccessFaultContract{ ErrorMessage = "Invalid user" };
throw new FaultException<DataAccessFaultContract>(fc);
}
return null;
}
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)
{
}
}
最后,使用适当的属性修饰您的操作:
[ServiceContract]
public interface IMyServiceContract
{
[Inspector]
[FaultContract(typeof(DataAccessFaultContract))]
[OperationContract]
MySeviceResponse FindAppointments(FindAppointmentRequest request);
...
}
调用服务时,客户端可以检查FaultException:
try
{
var response = client.FindAppointments(request);
}
catch (FaultException<DataAccessFaultContract> ex)
{
string errorMessage = ex.Detail.ErrorMessage;
// ...
}