本文标签:调用Web Services方法 ASP.NET
在Atlas中,它的“Web Services” 被放在了一个特殊的运行环境中执行(在某些情况下会委托给ASP.NET原有组件执行,这点在之前的文章中有过分析),因此,即使我们不是通过AJAX方式访问,只要了解Atlas那一套特殊的运行环境的行为,依旧能够给我们带来一些别的使用方式 。下面的示例就将使用Atlas服务器端对于Web Services调用的支持,来讲解如何使用HTTP GET来调用Web Services方法(除非特别说明,以下所有的解释均针对Atlas的扩展,而不是ASP.NET的原有Web Services支持) 。
首先,我们写一个Web Serivces方法: - [WebMethod]
- [WebOperation(true, ResponseFormatMode.Xml)]
- public XmlDocument Vote(string name, int id)
- {
- XmlDocument responseDoc = new XmlDocument();
responseDoc.LoadXml( "xml-stylesheet type=\"text/xsl\" href=\"Vote.xsl\"?>" + "<response><user>user><id>id>response>"); responseDoc.SelectSingleNode("//user").InnerText = name; responseDoc.SelectSingleNode("//id").InnerText = id.ToString(); return responseDoc; }
在Atlas中,HTTP POST为Web Services的默认支持方法,也是必然的支持方法 。而如果需要使该Web Service方法支持HTTP GET的话,就必须如上面代码一样,使用Microsoft.Web.Services.WebOperationAttribute进行标注 。 WebOperationAttribute的第一个参数就是getVerbEnabled,true则表示支持HTTP GET方法 。第二个参数Microsoft.Web.Services.ResponseFormatMode.Xml则表示结果对象的输出方式为 XML,而不是默认的JSON 。
在这里,我们使用XML的原因是因为JSON在这里没有任何意义 。返回JSON后是为了在获得这些内容之后通过Javascript函数eval执行,从而获得JSON表示的对象 。而在这里,我们的目的是将结果显示给用户看,所以使用XML形式返回,再加上XSL的支持,就能以HTML的形式显示给用户了 。
然后就是简单的XSL: - xml version="1.0" encoding="utf-8"?>
- <xsl:stylesheet version="1.0"
- xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
- <xsl:template match="/response">
- <html>
- <head>
- <title>Thanks for your participation.title>
- head>
- <body style="font-family:Verdana; font-size:13px;">
- <h4>Thanks for your participation.h4>
- <div>
- <xsl:text>Dear xsl:text>
- <xsl:value-of select="user"/>
- <xsl:text>, youve voted for item xsl:text>
- <xsl:value-of select="id"/>
- <xsl:text>.xsl:text>
- div>
- body>
- html>
- xsl:template>
- xsl:stylesheet>
接下来就是我们的HTML文件 。我们的目的非常简单,就是得到用户输入的信息,拼接成URL之后在新窗口中打开 。因此我们在这里根本无需使用Atlas 。代码如下: - <div>Name:<input type="text" id="txtName" />div>
- <div>Item:
- <select id="comboItem">
- <option value="1">Item 1option>
- <option value="2">Item 2option>
- <option value="3">Item 3option>
- <option value="4">Item 4option>
- <option value="5">Item 5option>
- select>
- div>
- <input type="button" value="Vote" onclick="vote()" />
点击“Vote”按钮后,就会调用Javascript函数Vote() 。代码如下: - <script language="javascript">
- function vote()
- {
- var url = "HttpGetWebService.asmx?mn=Vote";
- url += ("&name=" + encodeURI(document.getElementById("txtName").value));
- url += ("&id=" + document.getElementById("comboItem").value);
-
- window.open(url);
- }
- script>
我们需要拼接的URL很简单:首先使用在 QueryString里将mn设为我们即将调用Web Services方法名,然后就是在QueryString里调用Web Services方法所需的参数了 。请注意,既然是使用URL拼接,那么就必须使用encodeURI进行编码后才能使用,否则可能会出现异常情况 。以上介绍ASP.NET调用Web Services方法 。
|