The advantages of WebService are not much mentioned. XML is used as the data format and can interact with multiple applications across platforms and languages.
Today, we have added the Security Authentication Mechanism to WebService.
First, create an ASP. Net project and add a demoservice WebService to it.
/// <Summary> /// demoservice abstract description /// </Summary> [WebService (namespace = "http://tempuri.org/")] [webservicebinding (conformsto = wsiprofiles. basicprofile1_1)] [system. componentmodel. toolboxitem (false)] // to allow ASP. net Ajax calls this web service from the script. Please cancel the comments to the downstream. // [System. web. script. services. scriptservice] public class demoservice: system. web. services. webService {[webmethod] Public String helloworld () {return "Hello World ";}}
Everything is default. Then, we will add a Windows console project, add web references, add the WebService we just created to the project, and call the WebService.
Display result:
Next, we use the token to add security verification for WebService.
1. A new security order class, which inherits the soapheader. We use the soapheader for security verification.
/// <Summary> /// security verification token /// </Summary> public class securitytoken: soapheader {// security key public string key {Get; set ;}}
2. Modify the WebService class and support security verification
/// <Summary> /// demoservice abstract description /// </Summary> [WebService (namespace = "http://tempuri.org/")] [webservicebinding (conformsto = wsiprofiles. basicprofile1_1)] [system. componentmodel. toolboxitem (false)] // to allow ASP. net Ajax calls this web service from the script. Please cancel the comments to the downstream. // [System. web. script. services. scriptservice] public class demoservice: system. web. services. webService {// public token variable public securitytoken token; [webmethod] [soapheader ("token")] // declare that the security token Public String helloworld () {If (! This. isvalitoken () return string. empty; Return "Hello World ";} /// <summary> /// verify that the security token is correct /// </Summary> /// <returns> </returns> private bool isvalitoken () {bool flag = false; If (this. token! = NULL & this. Token. Key = "dotnetdev.cn") Flag = true; return flag ;}}
3. Modify the caller. Update the WebService reference and modify the code.
// Instantiate webserviceservicereference. demoservicesoapclient client = new servicereference. demoservicesoapclient (); // instantiate the token servicereference. securitytoken token = new servicereference. securitytoken (); // set the token key token. key = "dotnetdev.cn"; // call webserviceconsole. writeline (client. helloworld (token); console. readkey ();
Note: The method for adding a service reference is used here. The method for adding a web reference may be slightly different. However, the principle is the same.