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

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

<configuration>
  <system.web>
    <machineKey validationKey="AutoGenerate|value[,IsolateApps]" 
      decryptionKey="AutoGenerate|value[,IsolateApps]"
      validation="SHA1|MD5|3DES"/>

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
 
            rng.GetBytes(buff)
 
            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)))
            Next
 
            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()
MyKeyCreator.CreateMachineKey()

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"
decryptionKey="4252D6B2268.........67F451CE65D0F2ABE9BCD3A"
validation="SHA1"/>                             

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: 9/28/2010 4:22:28 AM
Comment:
Hi Dass - This is a nice article. Thank You.
Title: Hosting a .NET Application in a Web Farm   
Name: Gandhi Basnet
Date: 8/19/2010 9:58:13 AM
Comment:
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: 4/26/2010 3:05:58 AM
Comment:
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: 2/17/2010 3:21:34 AM
Comment:
Very useful and informative..explained the concept in short and sweet way.

Thanks!
Sanjivani
Title: mistake in your article   
Name: vishnu vardhan, Hyderabad.
Date: 1/4/2010 7:59:40 AM
Comment:
Please currect the word "Web Form" instead of "Web Farm".
I think it is not a web farm, it is Web form.

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

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

http://www.eggheadcafe.com/articles/GenerateMachineKey/GenerateMachineKey.aspx

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

Product Spotlight
Product Spotlight 





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


©Copyright 1998-2014 ASPAlliance.com  |  Page Processed at 10/1/2014 6:19:18 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search