Hosting a .NET Application in a Web Farm
page 4 of 7
by Tejaswini Das
Average Rating: 
Views (Total / Last 10 Days): 41126/ 76

1. Enable View State

In a Web farm, each client request can go to a different machine on every postback. Because of this behavior, you cannot leave the validationKey attribute set to AutoGenerate in the Machine.config file. Instead, you must set the value of the validationKey attribute to a fixed string that is shared by all the machines on the Web farm.

Generate Machine Key Elements for Web Farm

The <machineKey> Element configures keys to use for encryption and decryption of forms authentication cookie data and viewstate data, and for verification of out-of-process session state identification.

Here is an example of Configuration Structure for the element:

Listing 1

    <machineKey validationKey="AutoGenerate|value[,IsolateApps]" 

The validationKey attribute specifies the key used for validation of encrypted data. The validationKey is used when enableViewStateMAC is true to create a message authentication code (MAC) to ensure that the view state has not been tampered with. ValidationKey is also used to generate out-of-process, application-specific session ID's to ensure that the session state variables are isolated between sessions.

The keys created will be used for the validationKey and the decryptionKey attributes of the <machineKey> section in the <system.web> element in the Machine.config and the Web.config files.

Create the project

1. Start Microsoft Visual Studio .NET.

2. On the File menu, point to New and then click Project.

3. In the Project Types area, click Visual Basic Projects.

4. In the Templates area, click Console Application.

5. In the Name text box, type GenerateKey and then click OK.   

Write the code to generate the keys

In this program we will pass two parameters as command line arguments. The first argument is the number of bytes that will be used to generate decryption key and the second argument is the number of bytes used to generate the validation key.

The code uses a random number generator to create a random number of bytes based on the command-line arguments. After the random bytes are created, the bytes are formatted into a hexadecimal string that is suitable for use in the .config files.

1.      Add a new class file named KeyCreator to your Visual Basic project.

2.      Replace the existing code in the KeyCreator.vb file with the following code:

Listing 2

Imports System
Imports System.Text
Imports System.Security.Cryptography
Namespace Crypto
    Public Class KeyCreator
        Public Sub CreateMachineKey()
            Dim commandLineArgs As String()
            commandLineArgs = System.Environment.GetCommandLineArgs()
            Dim decryptionKey As String
            decryptionKey = CreateKey(System.Convert.ToInt32(commandLineArgs(1)))
            Dim validationKey As String
            validationKey = CreateKey(System.Convert.ToInt32(commandLineArgs(2)))
            Console.WriteLine( _
"<machineKey validationKey=""{0}"" decryptionKey=""{1}"" validation=""SHA1""/>", _
            validationKey, decryptionKey)
        End Sub
        Public Function CreateKey(ByVal numBytes As IntegerAs String
            Dim rng As RNGCryptoServiceProvider = New RNGCryptoServiceProvider()
            Dim buff(numBytes - 1) As Byte
            Return BytesToHexString(buff)
        End Function
        Public Function BytesToHexString(ByVal bytes As Byte()) As String
            Dim hexString As StringBuilder = New StringBuilder(64)
            Dim counter As Integer
            For counter = 0 To bytes.Length - 1
                hexString.Append(String.Format("{0:X2}", bytes(counter)))
            Return hexString.ToString()
        End Function
    End Class
End Namespace

3.      Open the Module1.vb file that is created by default and then add the following code in the Main sub routine.

Listing 3

Dim MyKeyCreator As New Crypto.KeyCreator()

4.      Save the application.

5.      Build the application.

Generate the hashes

Run the application from a command prompt and then pass in two integer values that are the size of the decryption and the validation keys. If you named the console application HashConfigVb.exe, type the following syntax at the command prompt in the Bin directory of the application: GenerateKey.exe 24 64.

The application should return output that is similar to the following:

Listing 4

<machineKey validationKey="08CE6B478DCE73..........E566D8AC5D1C045BA60"

Note: Because the code uses a random number generator, the output is different each time.

Update the configuration file

1. Locate the Machine.config file.

2. Locate the <system.web> section in the configuration file.

3. Replace the <machineKey> section with the output from the console application. If the <machineKey> section does not exist, create it.

4. Save the configuration file.

5. Restart IIS on all servers in the Web farm for the Machine.config changes to take effect.

View Entire Article

User Comments

Title: Nice Article   
Name: Fidha
Date: 2010-09-28 4:22:28 AM
Hi Dass - This is a nice article. Thank You.
Title: Hosting a .NET Application in a Web Farm   
Name: Gandhi Basnet
Date: 2010-08-19 9:58:13 AM
The article is superb. Now I understand web farm clearly and which session state is applicable for it. I was asked this question in a interview.

Thanks a lot.
Title: Conceptual and contextual mistakes in your article   
Name: Eriawan Kusumawardhono
Date: 2010-04-26 3:05:58 AM
There are quite numerous mistakes in your article.
They are:
- The article should be titled 'Hosting ASP.NET application..' instead of .NET application
- The article has no mention of the fact that load balancing configuration of IIS to be used in web farms has to be configured separately, and it can only be configured in Windows Server OS, not in client OS such as Windows XP or Vista.
- Using SQL Server to store ASP.NET session data means that you have to install this database server separated with the web servers, otherwise the intention of added performance will be nothing. Also the server farm of the web server has to point to the same db server.

It's true that you can't use in proc configuration easily in a web farm configuration, but it can be done.
Title: Nice article   
Name: Sanjivani
Date: 2010-02-17 3:21:34 AM
Very useful and informative..explained the concept in short and sweet way.

Title: mistake in your article   
Name: vishnu vardhan, Hyderabad.
Date: 2010-01-04 7:59:40 AM
Please currect the word "Web Form" instead of "Web Farm".
I think it is not a web farm, it is Web form.

with regards
Title: good work   
Name: Pawan Pawar
Date: 2009-11-30 2:22:17 AM
gr8 work...

i appericiate with article
Title: superb   
Name: praveen
Date: 2009-07-07 5:42:47 AM
Thanks Das for posting very informative and most useful article.
Title: Really Good   
Name: Milind Mahajan
Date: 2008-07-16 2:23:42 AM
really very good article. every dot net developer should read it... keep going
Title: Good one   
Name: Vishal Khanna
Date: 2008-05-14 2:14:01 PM
Thanks Mr. Das. Nice article. Good explanation of using Aspnet_regsql.exe.
Title: Another way to create key   
Name: ashu fouzdar
Date: 2008-04-28 8:27:24 AM
One can also use the following url for generating keys :

It is very nice web based key generater
Title: Good Job   
Name: Abhishek
Date: 2007-08-01 1:30:46 AM
Nice work. Keep it up :-)

Product Spotlight
Product Spotlight 

Community Advice: ASP | SQL | XML | Regular Expressions | Windows

©Copyright 1998-2021  |  Page Processed at 2021-02-27 4:40:43 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search