Home >Web Front-end >JS Tutorial >Detailed tutorial on jQuery Ajax calling WCF service_jquery
In the past two days, I have been writing a background framework based on WCF services. I encountered some setbacks in the process. After hard work, I have solved them all. I would like to share them with you. The tool used is Visual Studio 2013.
The backend needs to support transmitting and receiving data through json.
First, let’s talk about the construction process.
Step 1: Create WCF service application project WCF.
The second step is to create the data class 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(100)] public string LoginName { get; set; } [DataMember] [StringLength(100)] public string Password { get; set; } [DataMember] [DataType(DataType.Date)] public DateTime CreateDate { get; set; } } }
Here, since I use EF to interact with the database, I use Table, StringLength, and DataType. If you are not using EF, you don't need to add these. DataContract is used to mark that the current class needs to refer to the DataMember attribute when serializing. If DataContract is not set or only DataMember is set, all common attributes and fields will be serialized. Otherwise, only those with DataMember set will be serialized. Note that DataContract and DataMember have nothing to do with deserialization, that is, when a json object string is passed to the WCF service, it will be deserialized regardless of whether there is a DataMember on the field.
Step 3: Create service contract interface
If your service is only used to provide access to some non-WCF clients such as Ajax, then there is no need for an interface. Just add the various Attributes in the interface definition directly to the definition of the class provided by the service. But in order for the program to be accessible through the service interface, the interface must be used, for example: front-end MVC and back-end WCF architecture.
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); //服务功能2 [OperationContract] [WebGet(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)] bool CheckMan(string loginName); } }
The fourth step is to create a class that provides actual services based on the contract interface
Since my service needs to support Ajax, I selected the "WCF Service (Supports Ajax)" item. The specific code is as follows:
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. Interested partners can write a simple implementation by themselves.
The fifth step is to 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> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="jquery-1.10.2.js"></script> <script type="text/javascript" src="jqueryjson.js"></script> <title></title> </head> <body> <p> <input id="createPerson" type="button" value="POST_CreatePerson" /><br> <input id="checkMan" type="button" value="GET_CheckMan" /><br> <input type="text" id="loginName" /> <input type="text" id="password" /> </p> <script type="text/javascript"> $(document).ready(function () { $('#createPerson').click(function () { $.ajax({ type: "post", url: "personservice.svc/CreatePerson", data: '{"loginName":"' + $("#loginName").val() + '","password":"' + $("#password").val() + '"}', contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { alert("ID:" + data.d.ID + " Name:" + data.d.LoginName + " Password:" + data.d.Password + " CreateDate:" + data.d.CreateDate); }, error: function (xhr) { alert(xhr.responseText); } }); }); $('#checkMan').click(function () { $.getJSON("PersonService.svc/CheckMan", 'loginname="' + $("#loginName").val() + '"', function (data) { alert(data.d); }); }); }); </script> </body> </html>
It is recommended to use the createPerson button call method to write during the development process. It can feedback the actual error cause through the error callback function to facilitate debugging.
Step six, publish WCF service
Right-click the WCF project and select the "Publish" menu item, select "New Configuration File" from the drop-down list in the pop-up window, enter the configuration file name, click the "OK" button to enter the connection setting interface, as follows:
'
I publish in the IIS of this machine, so I choose the Web Deply publishing method. At the same time, it is recommended that the server and site names be set to: localhost and default web site/XXX. Here XXX can be defined by you as a service site. name (actually the name of the virtual directory of the IIS default site). In this way, after your development partner obtains the source code of the project, he can publish it to the exact same environment to avoid a series of problems caused by differences in environments.
After the settings are completed, click "Verify Connection". A green hook will appear, indicating that the settings are correct. Click "Publish".
Step 7, actual measurement
1. Now you can visit http://localhost/wcf/personservice.svc through the browser to confirm whether the server-side deployment is successful. The following interface appears, indicating that the deployment is successful.
2. Visit the test webpage http://localhost/wcf/post_get_test.html through the browser to check whether the function is OK.
Secondly, let’s talk about the various problems that occurred during the construction process.
1. When the web page calls the CreatePerson method of the service through Ajax, the method type is written incorrectly. POST is written as GET. As a result, the system reports: 405 (Method Not Allowed). In addition, according to the description on Microsoft's official website, a 405 error will also occur if you access a WCF WEB HTTP application (using WebHttpBinding and WebHttpBehavior services) through soap.
2. The contract attribute of the endpoint node in the web.config file is incorrectly configured and does not point to WCF.IPersonService. The page execution time is: 500 (System.ServiceModel.ServiceActivationException); in use http://localhost/wcf/ When personservice.svc checks the server-side deployment results, it reports: The contract name "VME.Contract.PersonService" cannot be found in the contract list implemented by the service "PersonService".
What needs to be explained here is that if your service is not based on an interface, the contract of the endpoint can directly point to the service class.
3. When using jQuery's ajax and transmitting values to the server in POST mode, due to a format error, the following error is reported: 500 (Internal Server Error). The detailed information is: When the formatter attempts to deserialize the message Throws an exception. There are two correct ways to handle it:
1) Pass it as json format object, for example:
What should be emphasized here is that in key-value pairs, the key must be enclosed in double quotes, and the case must be exactly the same as the formal parameter definition in the service method.
2) Pass it in the form of json format object string, as follows:
POST value
A) Pass in non-object parameters:
What needs to be emphasized here is that in key-value pairs, the key must be enclosed in double quotes, and the case must be exactly the same as the formal parameter definition in the service method. The value should be set according to the following rules: String enclosed in double quotes.
B) Pass in object parameters:
What should be emphasized here is that the case of the object attribute name must be completely consistent with the attribute definition of the data class.
Transfer value via GET
A) Pass in non-object parameters:
B) Pass in object parameters:
Finally, let’s talk about WCF debugging.
1. It is recommended to first confirm the success of the server-side deployment by visiting http://localhost/wcf/personservice.svc, and then conduct joint debugging between the client and server.
2. If you need code to run from the client to the server for joint debugging, you must use synchronous calls. Therefore, when using jQuery's ajax, async must be set to false.