Enable Ajax for WCF server and client applications

Source: Internet
Author: User

1. Take a look at the program structure and running test images as follows:

1. Program completion diagram:

2. Run:

Click "test" to call the WCF method. The call result is displayed.

II. Implementation Details: My Development Environment (vs2010,. net4, other versions have not been tested)

1. First create a webapp application, and then add the Ajax-enabled WCF Service,

Then add a test method. Note that [operationcontract] and [webget (requestformat = webmessageformat. JSON) are added to this method.] For details about webget labels, see: msdn.

Next, we need to modify the tag of this WCF class: [servicecontract (namespace = "")]
[Aspnetcompatibilityrequirements (requirementsmode = aspnetcompatibilityrequirementsmode. Allowed)]
[Javascriptcallbackbehavior (urlparametername = "jsoncallback")] pay special attention to the two labels.

Aspnetcompatibilityrequirements description:

When applied to a service implementation class, this attribute indicates whether the service requires ASP. Net compatibility mode or whether the compatibility mode is enabled for the host application domain (appdomain.

The AppDomains host service can run in two different host modes:

  • Hybrid transmission mode (default): In this mode, services are not involved in the ASP. net http pipeline. This ensures service behavior consistency, so that it is not affected by the host environment and transmission.

  • ASP. NET compatibility mode: In this mode, services participate in the ASP. net http pipeline in the same way as the asmx service class. ASP. NET functions (such as file authorization, URL Authorization, and HTTP session Status) are applicable to services running in this mode.

The host mode is controlled by the application-level Configuration flag aspnetcompatibilityenabled.

<System. servicemodel>

<Servicehostingenvironment aspnetcompatibilityenabled = "true"/>

</System. servicemodel>

By default, this flag is false. Therefore, the ASP. net service runs in hybrid transmission mode unless compatibility mode is explicitly selected.

For more information about ASP. NET compatibility mode, see servicehostingenvironment.

You can use the requirementsmode attribute to achieve this purpose. During running, the application can check whether ASP. NET compatibility mode is enabled by checking the value of the static attribute aspnetcompatibilityenabled.

Description of javascriptcallbackbehavior:

Jsonp is a mechanism used to enable cross-site scripting in Web browsers. Jsonp involves sending a request with the name of the callback function provided as the URL query string parameter value. The corresponding service returns a response containing the regular JSON load encapsulated in the call to the provided callback function (like a line of executable code ).

The following is an example of a service URL: http: // baseaddress/service/restservice? Callback = functionname. When the service is called, the Service uses the following JSON for response:

functionName({ “root”:”Something});

Javascriptcallbackbehaviorattribute allows developers to specify the name of the URL query string parameter to interpret it as a callback parameter. The default value is "Callback" (Case Insensitive ).

So far, the code of the WCF server has been completed.

2. Configure webconfig on the WCF server, paste the configuration file of the demo, and then explain it at 1.1:

<? XML version = "1.0" encoding = "UTF-8"?> <! -- Access the http://go.microsoft.com/fwlink/ for detailed messages about how to configure ASP. NET applications? Linkid = 169433 --> <configuration> <system. Web> <compilation DEBUG = "true" targetframework = "4.0"/> <! -- Add: authentication and set it to forms --> <Authentication mode = "forms"/> </system. web> <system. servicemodel> <behaviors> <endpointbehaviors> <behavior name = "WCF. demo. ajaxserviceaspnetajaxbehavior "> <enablewebscript/> </behavior> </endpointbehaviors> <! -- Add servicebehaviors --> <servicebehaviors> <behavior name = "enablemetadatabehaviors"> <servicemetadata httpgetenabled = "true"/> <servicedebug behavior = "true"/> </behavior> </ servicebehaviors> <! -- Add servicebehaviors: end --> </behaviors> <! -- Add bindings --> <bindings> <webhttpbinding> <binding name = "test" crossdomainscriptaccessenabled = "true"> </binding> </webhttpbinding> </bindings> <! -- Add bindings: end --> <servicehostingenvironment aspnetcompatibilityenabled = "true" multiplesitebindingsenabled = "true"/> <services> <! -- Add: behaviorconfiguration: Metadata for service --> <service name = "WCF. Demo. ajaxservice" behaviorconfiguration = "enablemetadatabehaviors"> <! -- Add: bindingconfiguration cross-origin for endpoint --> <endpoint address = "" behaviorconfiguration = "WCF. demo. ajaxserviceaspnetajaxbehavior "bindingconfiguration =" test "binding =" webhttpbinding "Contract =" WCF. demo. ajaxservice "/> </service> </services> </system. servicemodel> </configuration>

2.1 Add <Authentication mode = "forms"/> authentication using Forms

2.2 Add Server behavior configuration section

<! -- Add servicebehaviors -->
<Servicebehaviors>
<Behavior name = "enablemetadatabehaviors">
<Servicemetadata httpgetenabled = "true"/>
<Servicedebug includeexceptiondetailinfaults = "true"/>
</Behavior>
</Servicebehaviors>
<! -- Add servicebehaviors: end -->

Introduction to servicemetadata, from msdn

This configuration element allows you to control the metadata publishing function of the service. To prevent accidental leakage of potentially sensitive service metadata, the publishing of metadata is disabled by default for the Windows Communication Foundation (WCF) service. By default, this behavior is safe, but it also means that you cannot use the metadata import tool (such as svcutil.exe) to generate the client code required to call the service, unless the metadata publishing behavior of the service is explicitly enabled in the configuration. With this configuration element, you can enable this publishing behavior for the service.

For detailed code examples for configuring this behavior, see metadata publishing behavior.

Use optionalHttpgetbindingAndHttpsgetbindingAttribute. You can configure the binding to retrieve metadata through http get (or HTTPS get. If these two attributes are not specified, use the corresponding default binding as needed (When HTTP is usedHttptransportbindingelementWhen using httpsHttpstransportbindingelement. Note: These attributes cannot be used for built-in WCF binding. Only binding of internal binding elements that support ireplychannel is supported. In addition, the bound messageversion attribute must be none.

To reduce the possibility of service abuse by malicious users, you can use the SSL over HTTP (https) mechanism to ensure transmission security. Therefore, you must first bind an appropriate X.509 certificate to a specific port on the computer that hosts the service. (For more information, see working with certificates.) Then, add this element to the service configuration andHttpsgetenabledSet the featureTrue. FinallyHttpsgeturlThe URL of the Service metadata endpoint.

2.3 add webhttpbinding configuration for WCF

<! -- Add bindings -->
<Bindings>
<Webhttpbinding>
<Binding name = "test" crossdomainscriptaccessential abled = "true"> </binding>
</Webhttpbinding>
</Bindings>
<! -- Add bindings: end -->

Note that cross-origin settings must be enabled: crossdomainscriptaccessential abled = "true"

2.4 Add behaviorconfiguration information for the service and bindingconfiguration cross-origin configuration information for the endpoint

<! -- Add: behaviorconfiguration: Metadata for service -->
<Service name = "WCF. Demo. ajaxservice" behaviorconfiguration = "enablemetadatabehaviors">
<! -- Add: bindingconfiguration cross-origin for endpoint -->
<Endpoint address = "" behaviorconfiguration = "WCF. Demo. ajaxserviceaspnetajaxbehavior"
Bindingconfiguration = "test" binding = "webhttpbinding" Contract = "WCF. Demo. ajaxservice"/>
</Service>
</Services>

Now the development of the server is complete.

3. Client development

Create a test.html page and add jquery Class Library Reference <SCRIPT src = "scripts/jquery-1.4.1.min.js" type = "text/JavaScript"> </SCRIPT>, the demo uses the jquery1.4.1min version

It's easy to paste some HTML page code without explanation.

<HTML xmlns = "http://www.w3.org/1999/xhtml"> 

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.