HOW TO:指定組態中的服務繫結

在此範例中會定義基本計算機服務的 ICalculator 合約,該服務會在 CalculatorService 類別中實作,然後會在 Web.config 檔案中設定其端點,其中會指定服務使用 BasicHttpBinding。如需如何使用程式碼 (而非組態) 設定此服務的說明,請參閱 HOW TO:在程式碼中指定服務繫結

通常最佳作法是在組態中以宣告方式指定繫結和位址資訊,而不是在程式碼中強制指定。在程式碼中定義端點通常不是實際的作法,因為部署之服務的繫結和位址通常與開發服務時所使用的繫結和位址不同。比較一般性的作法是將繫結和位址資訊留在程式碼外面,如此一來,不需要重新編譯或重新部署應用程式,就可以變更繫結和位址資訊。

以下所有組態步驟都可以使用Configuration Editor Tool (SvcConfigEditor.exe) 進行。

如需這個範例的原始檔複本,請參閱Basic Binding Samples

指定用來設定服務的 BasicHttpBinding

  1. 定義服務類型的服務合約。

  2. 在服務類別中實作服務合約。

    ms733051.note(zh-tw,VS.90).gif注意:
    此服務的實作中不會指定位址或繫結資訊。同時,您不需要撰寫可從組態檔擷取該資訊的程式碼。

  3. 請建立 Web.config 檔,為使用 WSHttpBindingCalculatorService 設定端點。

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <system.serviceModel>
        <services>
          <service name=" CalculatorService" >
            <endpoint 
            <-- Leave the address blank to be populated by default-->
            <--from the hosting environment,in this case IIS, so -->
            <-- the address will just be that of the IIS Virtual -->
            <--Directory.-->
                address="" 
            <--Specify the binding type -->
                binding="wsHttpBinding"
            <--Specify the binding configuration name for that -->
            <--binding type. This is optional but useful if you  -->
            <--want to modify the properties of the binding. -->
            <--The bindingConfiguration name Binding1 is defined  -->
            <--below in the bindings element.  -->
                bindingConfiguration="Binding1"
                contract="ICalculator" />
          </service>
        </services>
        <bindings>
          <wsHttpBinding>
            <binding name="Binding1">
              <-- Binding property values can be modified here. -->
              <--See the next procedure. -->
            </binding>
          </wsHttpBinding>
       </bindings>
      </system.serviceModel>
    </configuration>
    
  4. 請建立 Service.svc 檔,其中包含下列這行文字,並且將它放入 Internet Information Services (IIS) 虛擬目錄中。

    <%@ServiceHost language=c# Service="CalculatorService" %> 
    

若要修改繫結屬性的預設值

  1. 若要修改 WSHttpBinding 的其中一個預設屬性 (Property) 值,請在 <wsHttpBinding> 項目內建立新的繫結組態名稱 <binding name="Binding1">,並且在此繫結項目中設定新的繫結屬性 (Attribute) 值。例如,若要將預設的開啟和關閉逾時值從 1 分鐘變更為 2 分鐘,請將下列文字加入至組態檔。

          <wsHttpBinding>
            <binding name="Binding1"
                     closeTimeout="00:02:00"
                     openTimeout="00:02:00">
            </binding>
          </wsHttpBinding>
    

請參閱

概念

使用繫結來設定服務和用戶端
指定端點位址