共用方式為


自動交易和 XML Web Service

ASP.NET 提供了內建支援,可使用與 Web Form 一致的程式設計抽象概念來建立和公開 XML Web Service。產生的模型為可設定大小且可延伸的,而且包括 HTTP、XML、SOAP 和 WSDL 開放的 Internet 標準等等。藉著支援開放的標準,任何用戶端或啟用 Internet 的裝置都可以存取和使用 XML Web Service。

XML Web Service 提供您在自動交易的範圍內執行程式碼的選項。交易能確保所有與資源管理員 (例如 SQL Server、MSMQ Server、Oracle Server 和 SNA Server) 的互動會保持執行穩固分散式應用程式所需的 ACID 屬性

您可以使用 WebMethodAttribute 屬性 (Attribute) 的 TransactionOption 屬性 (Property) 來宣告自動交易。若將 TransactionOption 屬性設定為 TransactionOption.RequiresNew,則每一次 XML Web Service 用戶端呼叫 XML Web Service 方法時,便會開始新的交易。

下列程式碼片段中說明的服務會公開名稱為 DeleteAuthor 的單一 XML Web Service 方法。這個 XML Web Service 方法會執行在自動交易範圍內的資料庫作業。

<%@ WebService Language="VB" Class="Orders" %>
<%@ assembly name="System.EnterpriseServices" %>

Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Services
Imports System.Web.Util
Imports System.EnterpriseServices

Public Class Orders
   Inherits WebService
   
   <WebMethod(TransactionOption := TransactionOption.RequiresNew)> _
Public Function DeleteAuthor(lastName As String) As Integer

      Dim deleteCmd As [String] = "DELETE FROM authors2 where au_lname='" 
         & lastName & "'"
      Dim sqlConn As New SqlConnection("Integrated Security=SSPI;database=pubs;server=myserver")
      Dim myCommand As New SqlCommand(deleteCmd, sqlConn)

      ' If a XML Web service method is participating in a transaction and 
      ' an exception occurs, ASP.NET automatically aborts the transaction.
      ' Likewise, if no exception occurs, then the transaction is
      ' automatically committed.
      myCommand.Connection.Open()
      Return myCommand.ExecuteNonQuery()
   End Function
End Class
[C#]
<%@ WebService Language="C#" Class="Orders" %>
<%@ assembly name="System.EnterpriseServices" %>

using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;
using System.Web.Util;
using System.EnterpriseServices;

public class Orders : WebService 
  {
     [ WebMethod(TransactionOption=TransactionOption.RequiresNew)]
     public int DeleteAuthor(string lastName)  
     {
       String deleteCmd = "DELETE FROM authors2 
          where au_lname='" + lastName + "'" ;
    
         SqlConnection sqlConn = new SqlConnection("Integrated Security=SSPI;database=pubs;server=myserver");
         SqlCommand myCommand = new SqlCommand(deleteCmd,sqlConn);

   // If a XML Web service method is participating in a transaction and an 
   // exception occurs, ASP.NET automatically aborts the transaction.
   // Likewise, if no exception occurs, then the transaction is
   // automatically  committed.

         myCommand.Connection.Open();
      return myCommand.ExecuteNonQuery();
     }
}

注意 只有當啟動的 XML Web Service 方法 (從用戶端呼叫的方法) 具有交易中繼資料時,交易才會開始。如果啟動的 XML Web Service 方法不包含適當的交易中繼資料,隨後的 XML Web Service 方法既不能參與現有的交易,也不能開始新的交易。

請參閱

自動交易 | 分散式交易 | 參與使用 ASP.NET 建立的 XML Web Service 中的交易