共用方式為


參數篩選條件

這個範例會示範如何驗證在方法被叫用前傳遞至該方法的參數。已定義 ParameterFilterAttributeParameterFilterBehavior,因此篩選條件就能夠套用至方法,使用該方法時,可以對傳遞至此方法的參數加上條件約束。

ms752267.note(zh-tw,VS.90).gif注意:
此範例的安裝程序與建置指示位於本主題的結尾。

服務會實作定義要求-回覆通訊模式的合約。合約是由 ICalculator 介面所定義,這個介面會公開數學運算作業 (加、減、乘、除)。

 // Define a service contract.
 [ServiceContract(Namespace="http://Microsoft.ServiceModel.Samples")]
 public interface ICalculator
 {
    [OperationContract]
    double Add(double n1, double n2);
    [OperationContract]
    double Subtract(double n1, double n2);
    [OperationContract]
    double Multiply(double n1, double n2);
    [OperationContract]
    double Divide(double n1, double n2);
 }

用戶端會對數學運算作業提出同步要求,服務則會以結果回覆。

在服務中,ParameterFilterBehavior 類別會實作 IParameterInspector 介面。介面的 BeforeCall 方法會完成實作,因此這些參數會在呼叫該方法前進行驗證。

internal class ParameterFilterBehavior : IParameterInspector
{
    double minValue;
    double maxValue;
    public ParameterFilterBehavior(double minValue, double maxValue)
    {
        this.minValue = minValue;
        this.maxValue = maxValue;
    }
    public void AfterCall(string operationName, object[] outputs,  
                          object returnValue, object correlationState)
    {
    }
    public object BeforeCall(string operationName, object[] inputs)
    {
        // validate parameters before call
        foreach (object input in inputs)
        {
            if ((input != null) && (input.GetType() == typeof(double)))
            {
                if ((double)input < minValue || (double)input > maxValue)
                {
                    throw new FaultException("Parameter out of range: " + input.ToString());
                }
            }
        }
        return null;
    }
}

ParameterFilter 會套用至 Multiply 方法,如下列範例程式碼所示:

[ParameterFilter(MaxValue = 10, MinValue = 1)]
public double Multiply(double n1, double n2)
{
    return n1 * n2;
}

當您執行範例時,作業要求和回應會顯示在用戶端主控台視窗中。在這個範例中,會有兩個作業送至服務。第一個乘法運算作業的輸入值介於 1 到 10 之間,所以該作業會成功。第二個乘法運算作業的輸入值超過此範圍,所以會將錯誤傳回用戶端,表示參數超出範圍。

Multiply(2,5.25) = 10.5
System.ServiceModel.FaultException: Parameter out of range: 81.25

Press <ENTER> to terminate client.

若要設定、建置及執行範例

  1. 請確定您已執行 Windows Communication Foundation 範例的單次安裝程序

  2. 若要建置方案,請遵循建置 Windows Communication Foundation 範例中的指示。

  3. 若要在單一或跨電腦的組態中執行本範例,請遵循執行 Windows Communication Foundation 範例中的指示。

Send comments about this topic to Microsoft.
© 2007 Microsoft Corporation. All rights reserved.