Sending Data using SOAP Header in Web Service

While writting Web Service in ASP.NET for our Business Layer, I came across a pattern where I found developers sending house keeping data as part of the method signature.

For e.g

CreateStockItem(int SessionID, int UserID, String StockItemXML)

I had a intution there will be better way of sending these data instead of the way we are sending and I came across the SOAP Header.

The following is the manner I implemented

1. Create a class derived from SoapHeader. The namespace is System.Web.Services.Protocols
public class InternalData:SoapHeader 
    public int SessionID;
    public   int UserID;

2. In the Web Service class create a object of above derived type. This should be public.
public class MyWebService: WebService
   public InternalData Header; 

3.  Add a SoapHeader attribute for a WebMethod indicating that the web method should be passed the SoapHeader data. Passed the name of the variable which will be filled by ASP.NET runtime
public string CreateStockItem(string StockItemXML)
     SessionID = Header.SessionID;
    UserID      = Header.UserID;

4. Program that consume web Service will create an instance of the Header

      InternalData myHeader = new InternalData();
      myHeader.SessionID = 12233;
      myHeader.UserID = 122;

5. Now create the object of the MyWebService

    MyWebService wsObj = new MyWebService();

6. Set the HeaderValue property of Webservice object to myHeader

   wsObj.HeaderValue = myHeader;

7. Call the Web Service method.

This will send the data in the header.


One Response

  1. That was gr88 and easy to understand…

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: