When writing a web service, you often perform security control on service access. There are many methods. Here is an example of how to use the SOAP header for control.
Step 1: reference the namespace needed
Using System;
Using System. xml;
Using System. xml. serialization;
Using System. Web. Services;
Using System. Web. Services. Protocols;
Step 2: create a custom soapheader class mysoapheaderPublic Class Mysoapheader: soapheader
{
String _ Name;
String _ Password;
Public String Name
{
Get {Return_ Name ;}
Set {_ Name=Value ;}
}
Public String Password
{
Get {Return_ Password ;}
Set {_ Password=Value ;}
}
}
Step 3: Create a webserivce. The myservice class has a public header of the mysoapheader type field. Before the customer calls the checkheader, a new instance is required for the header. The server checks the member information of the instance. If it fails, we will throw a soapheaderexception, a new instance of this exception. Here we call the constructor of two parameters. The first parameter is the cause of the custom exception. The second parameter uses soapexception. clientfaultcode to indicate that the customer's call format is incorrect or the necessary information is missing.
[WebService (namespace = " Http://DavidFan.cnblogs.com " )]
Public Class Myservice: system. Web. Services. WebService
{
Public Mysoapheader header;
[Soapheader ( " Header " , Direction = Soapheaderdirection. In)]
Public String Checkheader ()
{
If (Header = Null )
{
Throw NewSoapheaderexception ("Authentication failed", Soapexception. clientfaultcode );
}
Else
{
If (Header. Name ! = " Admin " | Header. Password ! = " Admin " )
{
Throw NewSoapheaderexception ("Authentication failed", Soapexception. clientfaultcode );
}
}
// Business logic.
Return " Something done " ;
}
}
Step 4: Call the client. Here, the mysoapheader and myservice class are the proxy classes generated by the WSDL tool, which correspond to the two classes on the server. First, we will create a new instance of mysoapheader, pay the header field of the new instance of myservice, and finally call the method of the server of checkheader, the header of the checkheader method! = NULL, and then verify the name and password.
The client first captures soapheaderexception (if any) in the try-Catch Block ). Then capture exception. Okay, this is only a few steps. Public Class Serviceclient
{
Protected Void Clientmethod ( String Name, String Password)
{
Mysoapheader H = New Mysoapheader ();
H. Name = Name;
H. Password = Password;
Myservice Service = New Myservice ();
Service. Header = H;
Try
{
StringRetval=Service. checkheader ();
Console. writeline ("Return:" +Retval );
}
Catch (Soapheaderexception soapex)
{
Console. writeline ("SOAP header exception:" +Soapex. Message );
}
Catch (Exception ex)
{
Console. writeline ("Exception:" +Ex. Message );
}
}
}
So far, we have simply introduced an example of using the SOAP header and expanded the application!
Next, we will introduce the soap extension! Thank you!