WCF与Flex的通信

来源:互联网 发布:c语言英航卡管理系统 编辑:程序博客网 时间:2024/05/01 05:03

Tutorial: Talking to WCF with Flex 3 via JSON or XML

Here is a simple tutorial to show you how you can get WCF (hosted in ASP.NET) talking to Flex 3. I used Visual Studio 2008 Pro, IIS 7 and Flex Builder 3 (beta 3). I did my initial inspection of the data moving back and forth with Fiddler2 and Firebug.

 

Let start with the C# WCF code. First you will need to open Visual Studio 2008 and select "File -> New Website". Then pick "ASP.NET Website" and for the "location" select "HTTP" and point it to your local IIS. In my case I picked "http://localhost/HelloServices". Then hit the "Ok" button. Also, if your doing this in Windows Vista then you will need to start Visual Studio in Administrator mode (right-click on the Visual Studio 2008 icon and pick the "Run as Administrator" option from the menu).

Once the project has been created right-click on the new website from the Solution Explorer and select "Add New Item" and select "AJAX-enabled WCF Service". Call the new file "Greeting.svc". Delete out the "DoWork()" method from the generated code. Then add a namespace to the file and call it "HelloServices". Also make sure to fill in the namespace for the "ServiceContract" attribute with "HelloServices" as well. Now we will add a simple method:

PLAIN TEXT
C#:
using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

 

namespace HelloServices
{

    [ServiceContract(Namespace = "HelloServices")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Greeting
    {
        // Add [WebGet] attribute to use HTTP GET
        [OperationContract]
        public String SayHello(String name)
        {
            return "Hello: " + name;
        }

        // Add more operations here and mark them with [OperationContract]
    }
}

 

Lets go ahead and test this out with the Default.aspx file before we make the Flex project.

Move over to the "Default.aspx" file and go into design mode. From the toolbox select the "AJAX Extensions" and drag over the "Script Manager". Then from the "HTML" section drag over an "Input (Button)" and drop it on the page. Double click that new input button and it will generate some JavaScript for us. Next, click on the Script Manager that we dragged over already and go into it's properties. Select the "Services" property and you should get a button with "...". Click on that button to open up the "ServiceReference Collection Editor". Press the "Add" button and in the "Path" property enter "Greeting.svc". Lets add the JavaScript now, your page should look like this:

PLAIN TEXT
ASP:
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
<script language="javascript" type="text/javascript">
// <!CDATA[

    function Button1_onclick()
    {
        var svc = new HelloServices.Greeting();
        svc.SayHello("Programmer", onSuccess, nullnull);
    }

    function onSuccess(data)
    {
        alert(data);
    }

// ]]>
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:ScriptManager ID="ScriptManager1" runat="server">
            <Services>
                <asp:ServiceReference Path="Greeting.svc" />
            </Services>
        </asp:ScriptManager>
    
    </div>
    </form>
    <p>
        <input id="Button1" type="button" value="button" onclick="return Button1_onclick()" /></p>
</body>
</html>

 

Now a couple important things. Remember when we added the namespace "HelloServices". We now need to make sure the web.config file and the Greeting.svc file both reflect that. Your Greeting.svc file should look like this:

PLAIN TEXT
ASP:
<%@ ServiceHost Language="C#" Debug="true" Service="HelloServices.Greeting" CodeBehind="~/App_Code/Greeting.cs" %>

 

The web.config section we are concerned about is the "system.serviceModel". Yours should look like this (its probably near the bottom of the web.config file):

PLAIN TEXT
XML:
<system.serviceModel>
        <behaviors>
            <endpointBehaviors>
                <behavior name="GreetingAspNetAjaxBehavior">
                    <enableWebScript/>
                </behavior>
            </endpointBehaviors>
        </behaviors>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
        <services>
            <service name="HelloServices.Greeting">
                <endpoint address="" behaviorConfiguration="GreetingAspNetAjaxBehavior" binding="webHttpBinding" contract="HelloServices.Greeting"/>
            </service>
        </services>
    </system.serviceModel>

 

Go ahead and run the project. When the Default.aspx page loads click on the button. You should see something like this:

wcf_result.jpg

Assuming that worked for you we can continue onto the Flex part of this tutorial. Open Flex Builder 3 and create a new "Flex Project" and call it "TalkToWCF". We won't add any GUI to this just to keep it simple. Make your MXML file looks like this:

PLAIN TEXT
XML:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" applicationComplete="URLRequestExample();" layout="absolute">
    
    <mx:Script>
        <![CDATA[
            import flash.events.*;
            import flash.net.*;

 

            private function URLRequestExample():void
            {
                var loader:URLLoader = new URLLoader();
                var header:URLRequestHeader = new URLRequestHeader("Content-Type", "application/json");
                
                configureListeners(loader);
    
                var request:URLRequest = new URLRequest("http://localhost/HelloServices/Greeting.svc/SayHello");
                request.method = URLRequestMethod.POST;
                request.requestHeaders.push(header);
                request.data = '{"name":"Programmer"}';
                
                try
                {
                    loader.load(request);
                    trace("Request sent");
                }
                catch (error:Error)
                {
                    trace("Unable to load requested document.");
                }
            }
    
            private function configureListeners(dispatcher:IEventDispatcher):void
            {
                dispatcher.addEventListener(Event.COMPLETE, completeHandler);
                dispatcher.addEventListener(Event.OPEN, openHandler);
                dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
                dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
                dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
                dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
            }
    
            private function completeHandler(event:Event):void
            {
                var loader:URLLoader = URLLoader(event.target);
                trace("completeHandler: " + loader.data);
            }
    
            private function openHandler(event:Event):void
            {
                trace("openHandler: " + event);
            }
    
            private function progressHandler(event:ProgressEvent):void
            {
                trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal);
            }
    
            private function securityErrorHandler(event:SecurityErrorEvent):void
            {
                trace("securityErrorHandler: " + event);
            }
    
            private function httpStatusHandler(event:HTTPStatusEvent):void
            {
                trace("httpStatusHandler: " + event);
            }
    
            private function ioErrorHandler(event:IOErrorEvent):void
            {
                trace("ioErrorHandler: " + event);
            }
        ]]>
    </mx:Script>
    
</mx:Application>

 

Run the Flex program in debug mode so you will see the trace statements since that is where the output is going. Hopefully you see this in the output:

flex_wcf.jpg

Down at the bottom is the JSON WCF returned to us - click on the image above if its too small to read.

Obviously a person can take this pretty far if you want to. The first thing would be to use the ActionScript CoreLib and parse the JSON coming back as well as encode the JSON you want to sent to WCF.

You can also have WCF send back XML rather than JSON. To do this you simply change your WCF method into this:

PLAIN TEXT
C#:
[OperationContract]
        [WebInvoke(ResponseFormat = WebMessageFormat.Xml)]
        public String SayHello(String name)
        {
            return "Hello: " + name;
        }

 

The result would be this:

PLAIN TEXT
XML:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Hello: Programmer</string>

原创粉丝点击