Vs2012.net WebService simple Create, use, validate, post-publish change reference address, Web reference, service reference

Source: Internet
Author: User

Work with more webservice, learn for a while, and summarize the process and understanding of using WebService in vs.

One creation (server side)

wearing a piece of webservice in VS is relatively straightforward. The steps are documented below.

Step 1: Create a new Web project, and note that it cannot be a class library.

Step 2: On the new Web project, add the new item--web service;

The automatically generated code is as follows:

<summary>    ///WebService1 Summary description///</summary> [WebService (Namespace = "/http// tempuri.org/")]    [webservicebinding (ConformsTo = wsiprofiles.basicprofile1_1)]    [ System.ComponentModel.ToolboxItem (false)]    //To allow the use of ASP. NET AJAX to invoke this Web service from a script, uncomment the following line.     //[System.Web.Script.Services.ScriptService] public    class WebService1:System.Web.Services.WebService    {        [WebMethod] public        string HelloWorld ()        {            return ' Hello world ';        }    }

Step 3: Write the WebService Service code;

Step 4: Publish the written code, the address after the run is the current WebService address;

over!


Two calls (client)

Directly on the process:

Step 1: On the project to add WebService, right-click Reference-Add Service reference;

Step 2: Note there are two ways to add WebService references, one is Web reference (Web reference), the other is called Service Reference (services reference); when adding, notice which is added. This is not a good description; direct. Represents a service reference ↓ (namespace customization, which is the namespace of the proxy class):



If you click on the "Advanced" button, then a Web reference will be added ↓ (PS: According to the instructions, the Web reference is the net2.0 version of the reference way, for compatibility to remain;):

Step 3: After adding the reference and setting the custom namespace, vs2012 will use the tool to automatically read the WSDL file based on the URL, then generate the proxy class, you can instantiate the object with the proxy class, and then work on it.

over!

Three authentication caller identity (WebService login)

There are basically several validation rules that use WebService: Validating the caller's IP address, validating the caller's account password with the SOAP header, and using SSL encryption authentication; Here is the method of validating with the SOAP header.

Step One: Add a class to the WebService service (this class acts as a vector for passing SOAP header account passwords; inherits from the abstract class: System.Web.Services.Protocols.SoapHeader). The code is as follows

namespace pointstorewebservice{///<summary>///This code is a large online, you can modify///</summary> public class as needed MySoapHeader:System.Web.Services.Protocols.SoapHeader {//<summary>////Tips: Don't want to use Automatic properties, there is a way to quickly generate properties: Qualifying the private member at the beginning of the loop, and then ctrl+r+e,vs2012 automatically constructs a property.//</summary> private string _userid = Stri Ng.        Empty;            public string UserId {get {return _userid;}        set {_userid = value;} private string _password = String.        Empty;            public string PassWord {get {return _password;}        set {_password = value;}        }///<summary>//non-parametric structure///</summary> public Mysoapheader () {}        <summary>///Structural structure///</summary>//<param name= "id" ></param> <param name= "pwd" ></param> public mysoapheader (string ID, string PWD) {Initial (ID, PWD);        }///<summary>//initialization///</summary>//<param name= "id" ></param> <param name= "pwd" ></param> public void Initial (string id, string pwd) {Us            Erid = ID;        PassWord = pwd;        }///<summary>///verification///</summary>//<param name= "id" ></param> <param name= "pwd" ></param>//<param name= "MSG" ></param>//<returns&             Gt;</returns> public bool IsValid (string ID, string Pwd,out string msg) {msg = "";            if (id = = "admin" && pwd = = "Admin") {return true;                } else {msg = "log error!";            return false;      }}///<summary>//heavy-duty//</summary>  <param name= "MSG" ></param>///<returns></returns> public bool IsValid (out str        ing msg) {return IsValid (_userid, _password, out msg); }    }}
Step Two: Add the members of the above type in the WebService service class;

  Public   

Step Three: Add a property on the method that needs to be validated: (Do not forget this step, otherwise the Mysoapheader class is not at the time of the call) [SoapHeader ("header")]

Step four: Call the methods in the Mysoapheader class to process control in the method that requires validation ....

Step Five: At the end of the call (/-\), instantiate an object of the Mysoapheader class first, Then give the object the validation attribute (here is the UserID, password to assign value;)

Step Six: pass the Mysoapheader class object to the past when using the proxy class object method;

PS: It is important to note that the method of passing SOAP headers differs depending on how vs2012 is added WebService, as follows:

① when you are in Web Reference mode: After instantiating the proxy class (assuming named: serviceobj), you can use the serviceobj.mysoapheadervalue=soap Header object name;

② when you are in service Reference mode: Proxy class object is not found Mysoapheadervalue of this property. Pass the SOAP header object as a parameter on the method that requires validation: serviceobj.methodname ( SOAP Header Object)

When this method has parameters, then this method automatically has a parameter, and in the No. 0 parameter position;
ove!!!

Four configuration methods for dynamically modifying the reference address after the software release

Note that I am using a new version of the service reference method;

When you add a service reference, an app. config file is generated under the corresponding project: (below)

<?xml version= "1.0" encoding= "Utf-8"?><configuration>    <configSections>    </ configsections>    <system.serviceModel>        <bindings>            <basicHttpBinding>                < Binding name= "Pointstoreservicesoap"/>            </basicHttpBinding>        </bindings>        <client >            <endpoint address= "http://localhost:25548/PointStoreService.asmx"                binding= "BasicHttpBinding" bindingconfiguration= "Pointstoreservicesoap"                contract= "Pointstoreservice.pointstoreservicesoap" Name= " Pointstoreservicesoap "/>        </client>    </system.serviceModel></configuration>
One of the things to note is:

<binding under the ①basichttpbinding node, a binding node is generated after a service reference is added daily.

A endpoint node is added to the endpoint of the ②client node, with each service reference added.

If adding a WebService referenced project is a class library, you will need to add a module of response under Web. config of the website for the class library to read. The following section is added in the Web. config configuration file:

<system.serviceModel> <bindings> <basicHttpBinding> <binding name= "1111111111111" Clo setimeout= "00:01:00" opentimeout= "00:01:00" receivetimeout= "00:10:00" sendtimeout= "00:01:00" allowCookies= "FA LSE "bypassproxyonlocal=" false "hostnamecomparisonmode=" StrongWildcard "maxbuffersize=" 6553600 " Maxbufferpoolsize= "52428800" maxreceivedmessagesize= "6553600" messageencoding= "Text" textencoding= "Utf-8" tra Nsfermode= "Buffered" usedefaultwebproxy= "true" > <readerquotas maxdepth= "" "Maxstringcontentl          Ength= "8192000" maxarraylength= "163840" maxbytesperread= "40960" maxnametablecharcount= "163840"/>                <security mode= "None" > <transport clientcredentialtype= "None" proxycredentialtype= "None" Realm= ""/> <message clientcredentialtype= "UserName" algorithmsuite= "Default"/> </secu Rity> </binding> </basicHttpBinding> </bindings> <client> <endpoint address= "http://11111111 11111111111111111.asmx "binding=" BasicHttpBinding "bindingconfiguration=" 11111111111 "contra ct= "1111111111111111" name= "11111111111"/> </client> </system.serviceModel>
The structure of the XML section above is the same as in the App. config configuration file, except that some attributes are added to restrict (the meaning of each property, you need to be able to check the Internet.) Obviously, the name property of the binding node and the endpoint node can be copied directly from App. Config.

over!

Vs2012.net WebService simple Create, use, validate, post-publish change reference address, Web reference, service reference

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.