ASP. NET 3.5 core programming learning notes (57): a WCF Service for Ajax applications

Source: Internet
Author: User

The WCF Service can output JSON and transmit data over HTTP (not necessarily using soap for data packaging ). What we need to do is to enable the endpoint to bind the model to webhttpbinding and enable web script calling through new features.

Build a simple WCF Service

Create a new web site in vs2008, add a new WCF Service, and name it timeservice.

Rewrite timeservice as a WCF Service

After adding a new project, we will find that there is another service endpoint (timeservice. SVC) in the project, and its related code files (such as wcftimeservice. CS) are located under the app_code file home. In addition, the web. config file will be modified to register the newly created service with the system.

Developers usually define service agreements through interfaces. Although this is not strictly required, we can implement multiple agreements in the same class through this method:

namespace Core35.Services.Wcf
{
//Contract
[ServiceContract(Namespace="Core35.Services", Name="WcfTimeService")]
public interface ITimeService
{
[OperationContract]
DateTime GetTime();
[OperationContract]
string GetTimeFormat(string format);
}
}

The itimeservice interface represents a service agreement. Servicecontract is used to mark protocols, and operationcontract is used to mark methods. For simpler cases, we can use class definition protocols (directly using servicecontract and operationcontract) and implement them directly.

Note that the namespace and name attribute values of the servicecontract feature are of great significance for Ajax-supported WCF services. The following is a class that implements the itimeservice protocol:

using System;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

namespace Core35.Services.Wcf
{
[AspNetCompatibilityRequirements(
RequirementsMode=AspNetCompatilityRequirementMode.Allowed)]
public class TimeService : ITimeService
{
public DateTime GetTime()
{
return DateTime.Now;
}
public class GetTimeFormat(string format)
{
return DateTime.Now.ToString(format);
}
}
}

Timeservice exposes two public endpoints: gettime and gettimeformat.

Register a WCF Service

The endpoint used to call this interface method is defined in the SVC file, such as the timeservice. SVC file:

<%@ ServiceHost Debug="true" Service="Core35.Services.Wcf.TimeService"
CodeBehind="~/App_Code/WcfTimeService.cs" %>

The servicehost command is used to indicate the name of the source file and the type of implementation of this method. If the service-related code is put in the SVC file in an inline way, you must specify the language attribute.

The final step is to register the service usage in the web. config file of the host ASP. NET application:

<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="TimeServiceAspNetAjaxBehavior">
<enableWebScript>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
<services>
<service name="Core35.Services.Wcf.TimeService">
<endpoing address=""
behaviorConfiguration="TimeServiceAspNetAjaxBehavior"
binding="webHttpBinding"
contract="Core35.Services.Wcf.ITimeService" />
</service>
</services>
</system.serviceModel>

First, register a series of behaviors of these endpoints. Therefore, it is declared that it can accept Web requests initiated through scripts. The enablewebscript element is logically equivalent to the scriptservice feature used to modify the Web service class.

Then, we will list the services that are sent to the current ASP. NET application.

Service Test

How can we use it on the ASP. NET page of the client? For developers, this is tantamount to calling Web Services.

First, register the SVC endpoint of the service with the script Manager:

<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/TimeService.svc" />
</Services>
</asp:ScriptManager>

When the script is processed, the scriptmanager control triggers an additional request to generate and download the Javascript proxy class for the specified WCF server.

The name of the proxy class depends on the namespace and name attributes of the servicecontract feature in the agreement. If these two attributes are not set and their default values are retained, the Javascript proxy class is named tempuri.org. itimeservice. Where tempuri.org is the default namespace and the interface name is the default name of the Protocol.

The name of the service class has no relationship with the name of the Javascript proxy class.

How to use JavaScript to call the WCF Service:

<script language="javascript" type="text/javascript">
function getTime()
{
Core35.Services.WcfTimeService.GetTimeFormat("dd-MM-yyyy [hh:mm:ss]", onMethodCompleted);
}
function onMethodComplete(results)
{
$get("lblCurrentTime").innerText = results;
}
</script>

Similar to ASP. NET Ajax Web Services, each JavaScript proxy method also supports one additional parameter-a callback function for processing successful or failed operations.

ASP. NET compatibility mode

When ASP. NET Ajax web is created, the service class is modified by the aspnetcompatibilityrequirements feature by default.

Although the messages of the WCF Service have nothing to do with the transmission protocol, if they are in the context of the ASP. NET Ajax application, they work very close to the asmx service. Through the aspnetcompatibilityrequirements attribute, we can enable the WCF and asmx services to work in the same model. Compatible with the asmx service, the WCF Service can access the httpcontext object and access other ASP. NET internal objects. This compatibility needs to be set at two levels. The first level is in the web. in the config file, set its servicehostingenvironment node. On the second layer, developers must explicitly select the compatibility mode for the WCF Service through the aspnetcompatibilityrequirements feature.

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.