Distributed Transactions with Web API across Application Domains

Introduction

 
WCF uses the [TransactionFlow] attribute for transaction propagation. This article shows a possible solution to obtain the same behavior with WebAPI in order to enlist operations performed in different application domains, permitting participation of different processes in the same transaction.
 

Building the Sample

 
In order to enlist transactions belonging to different application domains and event different servers, we can rely on Distributed Transaction Coordinators (DTC).

When the application is hosted on different servers, in order to use the DTC, those servers must be on the same Network Domain. DTC needs bidirectional communication, in order to coordinate the principal transaction with other transactions. Violation this precondition end up with the following error message:

The MSDTC transaction manager was unable to push the transaction to the destination transaction manager due to communication problems. Possible causes are: a firewall is present and it doesn't have an exception for the MSDTC process, the two machines cannot find each other by their NetBIOS names, or the support for network transactions is not enabled for one of the two transaction managers. (Exception from HRESULT: 0x8004D02A).

To check this precondition you can simply ping one server from another and vice-versa.
 
The DTC must be enabled for network access. The settings used for this example are shown in the following image:
 
Distributed Transactions With Web API Across Application Domains 
Distributed Transactions With Web API Across Application Domains
 
In the end, the DTC service must be running:
 
Distributed Transactions With Web API Across Application Domains
 

Description

 
With this example, I created a client WebAPI application working as a server. This endpoint exposes an action to save data posted from a client. The client, a console application, in addition, to call the WebAPI endpoint, perform an INSERT operation on its local database. Both those operations must be done in the same transaction, in order to commit or rollback all together.
 

Client application

The client application must initiate the transaction and then forward the transaction token to the WebAPI action method. To simplify this operation, I created an extension method on the HttpRequestMessage class that retrieves the transaction token from the ambient transaction and sets it as an HTTP header.
  1. public static class HttpRequestMessageExtension  
  2. {  
  3.     public static void AddTransactionPropagationToken(this HttpRequestMessage request)  
  4.     {  
  5.         if (Transaction.Current != null)  
  6.         {  
  7.             var token = TransactionInterop.GetTransmitterPropagationToken(Transaction.Current);  
  8.             request.Headers.Add("TransactionToken", Convert.ToBase64String(token));                  
  9.         }  
  10.     }  

Of course, this method must be invoked before calling the WebAPI endpoint and within a transaction context. For this reason, the client application must initiate the main transaction,
  1. using (var scope = new TransactionScope())  
  2. {  
  3.     // database operation done in an external app domain  
  4.     using (var client = new HttpClient())  
  5.     {  
  6.         using (var request = new HttpRequestMessage(HttpMethod.Post, String.Format(ConfigurationManager.AppSettings["urlPost"], id)))  
  7.         {  
  8.             // forward transaction token  
  9.             request.AddTransactionPropagationToken();  
  10.             var response = client.SendAsync(request).Result;  
  11.             response.EnsureSuccessStatusCode();  
  12.         }  
  13.     }  
  14.   
  15.     // database operation done in the client app domain  
  16.     using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionStringClient"].ConnectionString))  
  17.     {  
  18.         connection.Open();  
  19.         using (var command = new SqlCommand(String.Format("INSERT INTO [Table_A] ([Name], [CreatedOn]) VALUES ('{0}', GETDATE())", id), connection))  
  20.         {  
  21.             command.ExecuteNonQuery();  
  22.         }  
  23.     }  
  24.       
  25.     // Commit local and cross domain operations  
  26.     scope.Complete();  

WebAPI application

 
Server-side, I need to retrieve the transaction identifier and enroll the action method in the client transaction. I resolved it creating an action filter.
  1. public class EnlistToDistributedTransactionActionFilter : ActionFilterAttribute  
  2. {  
  3.     private const string TransactionId = "TransactionToken";  
  4.   
  5.     /// <summary>  
  6.     /// Retrieve a transaction propagation token, create a transaction scope and promote   
  7.     /// the current transaction to a distributed transaction.  
  8.     /// </summary>  
  9.     /// <param name="actionContext">The action context.</param>  
  10.     public override void OnActionExecuting(HttpActionContext actionContext)  
  11.     {  
  12.         if (actionContext.Request.Headers.Contains(TransactionId))  
  13.         {  
  14.             var values = actionContext.Request.Headers.GetValues(TransactionId);  
  15.             if (values != null && values.Any())  
  16.             {  
  17.                 byte[] transactionToken = Convert.FromBase64String(values.FirstOrDefault());  
  18.                 var transaction = TransactionInterop.GetTransactionFromTransmitterPropagationToken(transactionToken);  
  19.                   
  20.                 var transactionScope = new TransactionScope(transaction);  
  21.   
  22.                 actionContext.Request.Properties.Add(TransactionId, transactionScope);  
  23.             }  
  24.         }  
  25.     }  
  26.   
  27.     /// <summary>  
  28.     /// Rollback or commit transaction.  
  29.     /// </summary>  
  30.     /// <param name="actionExecutedContext">The action executed context.</param>  
  31.     public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)  
  32.     {  
  33.         if (actionExecutedContext.Request.Properties.Keys.Contains(TransactionId))  
  34.         {  
  35.             var transactionScope = actionExecutedContext.Request.Properties[TransactionId] as TransactionScope;  
  36.   
  37.             if (transactionScope != null)  
  38.             {  
  39.                 if (actionExecutedContext.Exception != null)  
  40.                 {  
  41.                     Transaction.Current.Rollback();  
  42.                 }  
  43.                 else  
  44.                 {  
  45.                     transactionScope.Complete();  
  46.                 }  
  47.   
  48.                 transactionScope.Dispose();  
  49.                 actionExecutedContext.Request.Properties[TransactionId] = null;  
  50.             }  
  51.         }  
  52.     }  

Now we can apply this filter on our action endpoint in order to participate in the caller transaction.
  1. [HttpPost]  
  2. [EnlistToDistributedTransactionActionFilter]  
  3. public HttpResponseMessage Post(string id)  
  4. {  
  5.     using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString))  
  6.     {  
  7.         connection.Open();  
  8.   
  9.         using (var command = connection.CreateCommand())  
  10.         {  
  11.             command.CommandText = String.Format("INSERT INTO [Table_1] ([Id], [CreatedOn]) VALUES ('{0}', GETDATE())", id);  
  12.             command.ExecuteNonQuery();  
  13.         }  
  14.     }  
  15.   
  16.     var response = Request.CreateResponse(HttpStatusCode.Created);  
  17.     response.Headers.Location = new Uri(Url.Link("DefaultApi"new { id = id }));  
  18.     return response;  

Source Code Files

 
Attached to this article, you can find a solution containing two projects: a client console application and a WebAPI application.
 
To try this solution, unzip the solution and deploy the WebAPI 2.0 application under IIS on server "A" with its own SQL Server instance. After that, install the console application on server "B" with its own SQL Server instance. As mentioned before, those servers must be in the same Network Domain.
 
The client application test four cases,
  • Commit client and server
  • Rollback client and server
  • Exception server-side (resulting in a server and client rollback)
  • Exception client-side (resulting in a server and client rollback)
When the client application starts, it asks you what kind of test do you want. In case of a positive commitment (0), a green message is reported, followed by a server call used to get all records inserted since now,
 
Distributed Transactions With Web API Across Application Domains
 
In negative cases (1,2,3), the resulting message will be in red, followed by a server call to retrieve all the records from the server DB to check that no new record was inserted.
 
Distributed Transactions With Web API Across Application Domains


Similar Articles