Tuesday, March 27, 2012

Add SOAP Header to your XML WebService

This will show how to add a SOAP Header to a WebService.
//namespace
using System.Web.Services.Protocols;

Creating the Header.
Create a Class which is Inherited from SoapHeader Class.


public class UserAuthHeader : SoapHeader
{
public string UserName;
public string Password;
}



[WebService(Namespace = "http://www.smilu.net/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 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 Service : System.Web.Services.WebService
{
public UserAuthHeader userauthentication;
public Service () {

//Uncomment the following line if using designed components
//InitializeComponent();
}

[WebMethod,SoapHeader("userauthentication")]
public string HelloWorld() {
if (userauthentication.UserName == "smilu" && userauthentication.Password == "pass")
{
return "Hello World";
}
else
{
return "access denied";
}

}

}



-------------------------------------------------------------------------------------

For calling the same inside a Website check the code below

protected void Button1_Click(object sender, EventArgs e)
{
WithHeader.Service sc = new WithHeader.Service();
WithHeader.UserAuthHeader uh = new WithHeader.UserAuthHeader();
uh.UserName = "smilu";
uh.Password = "pass";
sc.UserAuthHeaderValue = uh;
Response.Write(sc.HelloWorld());
}

Here UserAuthHeader is the Class name of the Header which we created.