pavanarya

Let us share the knowledge

Soap Headers in WebServices

with one comment

Hi,
Now a days communication between heterogeneous applications plays a vital role. We are having different modes for achieving this communication. One of the most important one among them is Web Services.
Web Services uses xml as a format for the purpose of communication and this xml is called as Soap message. Soap has a specific format.

Soap Format

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header>
    <TestSoapHeader xmlns="http://tempuri.org/">
      <username>string</username>
      <password>string</password>
    </TestSoapHeader>
  </soap:Header>
  <soap:Body>
    <HelloWorld xmlns="http://tempuri.org/" />
  </soap:Body>
</soap:Envelope>

Soap format consists of a root element called Envelope.Inside the envelope we have two main nodes.
1.Header node
2.Body node

Header node is optional and can have some data which is either specific to the service or not specific to the service.

Body node is a compulsory node and it contains the information related to the web method.

Now let us discuss about the soap header tag and its customization

Soap Header
Let us consider a scenario that requires the usage of soap Headers.
Generally we are having a web service that deals with some sensitive data like bank accounts. So i am having a web service that contains a web method ShowBalance() and it takes an input username. So based on the username it will return the amount present in his account.
If the web service is public then anyone can make use of that. So i’ll randomly try to send user names to the web method ShowBalance() and if any username matches with the database then it will return the account info.
So in order to prevent this i am planning to make use of SoapHeaders.
So whenever an application is trying to make use of my web service they are supposed to send some information in the soap headers and i’ll validate those soap headers in my webservice to make sure that the web service call is from intended users and then i’ll start processing the account information.

Working with SoapHeaders involves multiple steps and let us dicuss them in detail.

1.Creating a WebService

Now let us create a webservice with a webmethod called ShowBalance()

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

namespace SOAPHEADEREXAMPLE
{
    /// <summary>
    /// Summary description for MyWebService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(Name = "Test", ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]

    public class MyWebService : System.Web.Services.WebService
    {
        [WebMethod]
        public string ShowBalance(string user)
        {
            //Code to show balance
            return "Balance in Rupees";
        }
    }
}

Now we are done with the web service creation.

2.Adding a class that inherits SoapHeader

i.In order to manipulate the soap header of the soap xml. First we are supposed to create a class that inherits the SoapHeader class. SoapHeader class is present in the “System.Web.Services.Protocols;”

ii. After declaring the class we are supposed to add public properties inside the class. These properties data will be transmitted in the form of xml nodes inside the node

public class TestSoapHeader : SoapHeader
    {
       public string username = "";
       public string password = "";
    }

In my case i am having a class called TestSoapHeader with two properties username and password.
The soap header format will be as follows

<soap:Header>
    <TestSoapHeader xmlns="http://tempuri.org/">
      <username>string</username>
      <password>string</password>
    </TestSoapHeader>
  </soap:Header>

3.Using SoapHeaderClass properties in the actual web method

Now in order to make use of the soap header content in the actual web methods we are supposed to follow few steps.

  public class MyWebService : System.Web.Services.WebService
    {
        public TestSoapHeader soapHeadr;
        [WebMethod]
        [SoapHeader("soapHeadr", Required = true)]
        public string ShowBalance(string user)
        {
            string username=soapHeadr.username;
            string pass = soapHeadr.password;
            //Code to process balance
            return "Show Balance In Rupees";
        }
    }

i.Create an object of the SoapHeaderclass in our case TestSoapHeader Class.
ii. We are supposed to decorate the web method with an attribute [SoapHeader("name of the obj created in the above step",Required="true")]

SoapHeader attribute takes two values.
a.Object of the class that implemented SoapHeader class(in our case soapHeadr)
b.Required attribute
Note: Required attribute is obsolete and in future versions it is not mandatory.

Now we can make use of the soap header class properties in the web method. So in my sample web method ShowBalance()
I am retrieving the username and password from the soap header(these values are sent from the client end) and based on those values i am performing oprations.

Entire Source code of the Web Service

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

namespace SOAPHEADEREXAMPLE
{
    /// <summary>
    /// Summary description for MyWebService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(Name = "Test", ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]

    public class TestSoapHeader : SoapHeader
    {
       public string username = "";
       public string password = "";
    }
    public class MyWebService : System.Web.Services.WebService
    {
        public TestSoapHeader soapHeadr;
        [WebMethod]
        [SoapHeader("soapHeadr", Required = true)]
        public string ShowBalance(string user)
        {
            string username=soapHeadr.username;
            string pass = soapHeadr.password;
            //Code to process balance
            return "Show Balance In Rupees";
        }
    }
}

Now we are done with the implementation from web Service end.

Working With Soap Headers From Client End

Now we are trying to access a web service which performs operations based on the username and password sent using the soap headers.

1.Create a web project and add our web service as web reference.
2. I am creating an aspx page and i am trying to make use of our web service the aspx.cs

Create an object of the class MyWebService that contains the actual web method(ShowBalance())
Create an object of the class that implemented SoapHeader class(in our case TestSoapHeader class)
Now assign values to the TestSoapHeader class properties.

There is a property called TestSoapHeaderValue in the web service class. Now assign the TestSoapHeader class object to this property as follows.

localhost.MyWebService service = new localhost.MyWebService();

            localhost.TestSoapHeader header = new localhost.TestSoapHeader();
            header.username = "pavanarya";
            header.password = "password@123";
            service.TestSoapHeaderValue = header;

Note: TestSoapHeaderValue is the property created by the framework.This is the member variable of the proxy class. Until and unless we assign our header object to this property the data will not be transmitted to the web service as a soap header.

Complete code from client end

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication
{
    public partial class usingwebservice : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            localhost.MyWebService service = new localhost.MyWebService();

            localhost.TestSoapHeader header = new localhost.TestSoapHeader();
            header.username = "pavanarya";
            header.password = "password@123";
            service.TestSoapHeaderValue = header;
            service.ShowBalance("pavan");
        }
    }
}

Now we are sending username and password inside the soapheader and in the webservice we are going to authenticate the caller of the web service.
With this approach we can increase the security of our web services to some extent.

Format of final Soap XML

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header>
    <TestSoapHeader xmlns="http://tempuri.org/">
      <username>string</username>
      <password>string</password>
    </TestSoapHeader>
  </soap:Header>
  <soap:Body>
    <ShowBalance xmlns="http://tempuri.org/">
      <user>string</user>
    </ShowBalance>
  </soap:Body>
</soap:Envelope>
About these ads

Written by pavanarya

May 15, 2012 at 11:53 am

Posted in Asp.net, WebServices

One Response

Subscribe to comments with RSS.

  1. [...] In this post you can see how to create a web service with custom soap headers But there i am calling the web service from aspx page but in this post i am making using of html and plain js. [...]


Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 68 other followers

%d bloggers like this: