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:
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:
<!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, null, null);
}
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:
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):
<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:
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:
<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:
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:
[WebInvoke(ResponseFormat = WebMessageFormat.Xml)]
public String SayHello(String name)
{
return "Hello: " + name;
}
The result would be this:
- WCF与Flex的通信
- FLEX 与 .net wcf /web services通信
- Silverlight与WCF的双工通信
- Silverlight与WCF之间的通信(2)利用WCF的双工通信“推送”给SL数据
- flex与.Net的socket通信
- flex与.Net的HTTPSerivce通信
- Flex与.Net的WebService通信
- Flex与webservice的通信(一)
- Java与Flex间的通信构造
- Flex与服务器端的通信方式
- flex与flash的fscommand通信
- flex与java的一种通信方式
- Flex与Java的交互通信
- flex与JAVA的SOCKET通信
- WCF的通信模式
- flex与xml通信
- Flex与WebService通信
- Flex 与 servlet 通信
- 在UltraEdit的查找和替换中使用正则表达式
- Wiseinstallation打安装包
- MTK的智能芯片MT6516
- rails undefined method `each’ for
- 在UltraEdit中使用正则表达式
- WCF与Flex的通信
- SQL Server数据类型对应的JDBC数据类型(java.sql.Types)和Java数据类型
- pku 1222 熄灯
- ORACLE游标
- 安装php扩展
- GDI+ 制作饼图 或者其他 请给些例子说明 :
- 10个新的最有前途的JavaScript框架
- 搜索引擎测试方法
- C++ 过滤特殊字符