JQuery Ajax invoke WCF service detailed tutorial _jquery

Source: Internet
Author: User
Tags serialization tojson

These two days in writing based on WCF Service background framework, the process encountered a number of setbacks, through efforts to all resolved, here to share with you, the tool used is visual Studio 2013.

This background requires support for passing and receiving data through JSON.

First of all, talk about the construction process.

First step: 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 (MB)]
    public string LoginName {get; set;}

    [DataMember]
    [Stringlength (MB)]
    public string Password {get; set;}

    [DataMember]
    [DataType (datatype.date)]
    Public DateTime createdate {get; set;}}}


Here, because I use EF to interact with the database, I use table, Stringlength, and DataType. If you do not use EF, you can not add these. DataContract is used to flag that the current class needs to refer to the DataMember property when serializing, and if no datacontract is set or only DataMember is established, all common properties and fields are all serialized, otherwise only datamember serialization is set. Note that DataContract and DataMember are not related to deserialization, which means that when a JSON object string is passed to the WCF service, it is deserialized regardless of whether there is a datamember on the field.

Step three: Create a service Contract interface

If your service is intended only to provide access to some non-WCF clients, such as Ajax, then you do not need an interface to add the various attributes in the interface definition directly to the definition of the class provided by the service. However, in order for the program to be accessible through the service interface, you must use an interface, such as a front-end mvc+ background WCF architecture form.

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 = Web messagebodystyle.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);
}

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

Because my service needs AJAX support, select the WCF services (AJAX-enabled) entry, which 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 PERSONBLL is the business logic layer used to actually process data, and interested partners can write a simple implementation of their own.

The fifth step is to create a Web client.

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

<! DOCTYPE html>  

It is suggested that the Createperson button invocation should be used to write in the development process, and the error callback function can be used to feed back the actual error causes and facilitate debugging.

Step sixth, publish the WCF service

Right-click the WCF Project Select the Publish menu item, select "New profile" in the Drop-down list in the pop-up window, enter the name of the profile, and click the "OK" button to enter the connection setup interface as follows:

'

I was published in my native IIS, so I chose the Web Deply publishing method, and it is recommended that the server and site names be set to: localhost and Default Web site/xxx, Here xxx can be defined by your own name of the Service site (is the virtual directory name of the IIS default site), so that your development partners to obtain the project source code, can be published in the same environment, to avoid the differences in the environment to extend a series of problems.

After setting up, click "Verify Connection", appear the green hook hook, the description set correctly, click "Publish" can.

Seventh step, measured

1, now can be accessed through the browser Http://localhost/wcf/personservice.svc to confirm the success of the server-side deployment, the following interface shows the successful deployment.

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

Secondly, the following is a discussion of the various problems that arise in my construction process.

1, the Web page through the AJAX Call service Createperson method when the method type is wrong, post written a GET, results system: 405 (method is not allowed). Also, according to Microsoft's website, 405 errors can occur if you access a WCF WEB HTTP application via SOAP (services using WebHttpBinding and WebHttpBehavior).

2, Web.config file Endpoint node contract property configuration error, does not point to wcf.ipersonservice, web implementation times: 500 ( System.ServiceModel.ServiceActivationException); When verifying server-side deployment results with HTTP://LOCALHOST/WCF/PERSONSERVICE.SVC, report: In service Personservice "contract name" VME not found in the list of implemented contracts. Contract.personservice ".

The point here is that if your service is not based on interfaces, then the endpoint contract directly to the service class.

3, in the use of jquery Ajax and the post way to the server, due to the format error, reported the following error: (Internal Server error), details are: The formatter attempts to deserialize the message throws an exception. There are two ways to handle it correctly:

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

Copy Code code as follows:

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

The emphasis here is on key-value pairs, where the keys must be double quotes, and the case must be exactly the same as the parameters defined in the service method.
2 is passed as a JSON-formatted object string, as follows:

Post Method Pass Value

(A) Incoming non-object parameters:

Copy Code code as follows:

{"LoginName": "Name", "Password": "pwd"} '

The emphasis here is that the key must be double quotes, 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 quotes.
(B) Incoming object parameters:

Copy Code code as follows:

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

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

Get method Pass Value

(A) Incoming non-object parameters:

Copy Code code as follows:

' Loginname= ' name '

(B) Incoming object parameters:

Copy Code code as follows:

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

Finally, talk about WCF debugging.

1. It is recommended that the server-side deployment be validated first through the access Http://localhost/wcf/personservice.svc, and then the client and server-side cascade.

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

Related Article

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.