Using jquery Ajax to invoke WCF service programming experience

Source: Internet
Author: User
Tags tojson microsoft website

These two days in writing based on the WCF Service background framework, the process encountered some setbacks, after efforts to solve all, to share here, you use the tool is Visual Studio 2013.

The background needs support for passing and receiving data through JSON.


First of all, talk about the building process.

First step: Create a WCF Service Application project WCF.



The second step is to create the data classes used by the service

Using system;using system.componentmodel.dataannotations;using system.componentmodel.dataannotations.schema;using System.runtime.serialization;namespace wcf{    [DataContract]    [Table ("TUser")] public    class person    {        [DataMember] public        int ID {get; set;}        [DataMember]        [Stringlength (+)]        public string LoginName {get; set;}        [DataMember]        [Stringlength (+)]        public string Password {get; set;}        [DataMember]        [DataType (datatype.date)]        Public DateTime createdate {get; set;}}    }
Here, because I used EF to interact with the database, I used table, Stringlength, DataType. If you are not using EF, you can do this without adding these. DataContract is used to flag that the current class needs to refer to the DataMember property when serializing, and if no datacontract or only DataMember is set, all common properties and fields are serialized, otherwise only datamember serialization is set. Note that DataContract and DataMember are not related to deserialization, that is, when a JSON object string is passed to a WCF service, it is deserialized regardless of whether there are datamember on that field.

Step three: Create a service Contract interface

If your service is used only to provide access to some non-WCF clients such as Ajax, then the interface is not required, and the various attribute in the interface definition are added directly to the definition of the class provided by the service. However, in order for the program to be accessible through the service interface, the interface must be used, for example: front-end mvc+ the schema of the backend WCF.

Using system.collections.generic;using system.servicemodel;using system.servicemodel.web;namespace WCF{    [ ServiceContract] public    interface Ipersonservice    {        [OperationContract]        [WebInvoke (Method = "POST", Requestformat = Webmessageformat.json, Responseformat = Webmessageformat.json, bodystyle = webmessagebodystyle.wrappedrequest)] Person        Createperson (string loginName, string password);        Service Function 2        [OperationContract]        [WebGet (Requestformat = Webmessageformat.json, Responseformat = Webmessageformat.json, bodystyle = webmessagebodystyle.wrappedrequest)]        bool Checkman (string loginName);}    }

Fourth, create a class that provides the actual service based on the contract interface


Because my service needs to support Ajax, select the "WCF Service (AJAX-enabled)" entry with the following code:

Using system;using system.collections.generic;using system.servicemodel.activation;namespace WCF{    [ Aspnetcompatibilityrequirements (Requirementsmode = aspnetcompatibilityrequirementsmode.allowed)] public    class Personservice:ipersonservice    {public person        Createperson (string loginName, string password)        {            return new PERSONBLL (). Createperson (Loginname,password);        }        public bool Checkman (string loginName)        {            return new PERSONBLL (). Checkman (LoginName);}}}    

The above PERSONBLL is the business logic layer used to actually process data, and interested partners can write a simple implementation of their own.


Fifth step, create a Web client.

In order to avoid dealing with cross-domain issues, the Web page post_get_test.html is placed under the WCF project.

<! DOCTYPE html>

It is suggested to adopt the Createperson button call method in the development process to write, which can be used to feedback the actual cause of error by error callback function, and convenient debugging.


Sixth step, publish the WCF service

Right-click the WCF Project Select the "Publish" menu item, in the Pop-up window drop-down list select "New Profile", enter the profile name, click "OK" button to enter the connection settings interface, as follows:


I was published in the native IIS, so choose the Web Deply publishing method, at the same time, it is recommended that the server and site name is set to: localhost and the default Web Site/xxx, Here xxx can be defined by yourself the name of the Service site (which is actually the virtual directory name of the IIS default site), so that your development partner gets to the project source code, can publish to the exact same environment, avoid due to the environmental differences to extend a series of problems.

After setting up, click "Verify Connection", the green hook will appear, the setting is correct, click "Publish".


The seventh step, measured

1, now can be accessed through the browser http://localhost/wcf/personservice.svc to confirm the server-side deployment is successful, the following interface shows that the deployment was successful.


2, through the browser Access test page http://localhost/wcf/post_get_test.html to check whether the function is OK.


Secondly, the following is a list of the problems I have in the construction process.

1, the Web page through the AJAX Call service Createperson method to write the method type is wrong, post written to get, the results of the system reported: 405 (Method not allowed). Also, according to the Microsoft website, a 405 error can occur if you access a WCF WEB HTTP application via SOAP (using webhttpbinding and WebHttpBehavior services).

2. The contract property of the endpoint node in the Web. config file is misconfigured and does not point to Wcf.ipersonservice, page execution times: 500 ( System.ServiceModel.ServiceActivationException); When verifying server-side deployment results with HTTP://LOCALHOST/WCF/PERSONSERVICE.SVC, the report: in the Service " Personservice "contract name not found in the implemented Contracts list" VME. Contract.personservice ".

It is necessary to note that if your service is not based on an interface, then the endpoint contract directly points to the service class.

3, when using jquery Ajax and post to the server, due to the format error, the following error: Internal server error, the details are: The formatter attempts to deserialize the message when an exception is thrown. There are two ways to handle it correctly:

1) is passed as a JSON-formatted object, for example:

{"LoginName": "Name", "Password": "PWD"}

The emphasis here is on key-value pairs, where the key must be double-quoted, and the case must be exactly the same as the parameter definition in the service method.

2) is passed as a JSON-formatted object string, as follows:

Post Mode transfer value

A) pass in non-object parameters:

<pre name= "Code" class= "JavaScript" > ' {"loginName": "Name", "Password": "pwd"} '
The emphasis here is on key-value pairs, where the key must be double-quoted, and the case must be exactly the same as the parameter definition in the service method, and the value should be set as follows: string with double quotation marks.

B) Incoming object parameters:

var person = {};p Erson. LoginName = $ ("#loginName"). Val ();p Erson. Password = $ ("#password"). Val (); var Jsonperson = ' {' person ': ' + $.tojson (person) + '} ';

It is important to emphasize that the case of the object property name must be exactly the same as the property definition of the data class.

Get method Pass Value

A) pass in non-object parameters:
' Loginname= ' name '
B) Incoming object parameters:
var person = {};p Erson. LoginName = $ ("#loginName"). Val ();p Erson. Password = $ ("#password"). Val (); var Jsonperson = ' person= ' + $.tojson (person);

Finally, talk about WCF debugging.

1, it is recommended to first verify the server-side deployment through the form of Access http://localhost/wcf/personservice.svc, and then the client and server-side-linked tune.

2. If you need code to run from the client until the server side runs for a tune-up, you must use synchronous invocation, so async must be set to False when using jquery Ajax.


Using jquery Ajax to invoke WCF service programming experience

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.