0
我想爲WCF服務和html頁面之間的通信編寫一個簡單的「Hello world」示例。WCF(ServiceHost)和HTML(JQuery)之間的通信
要編程我用下面的代碼的WCF服務器:
namespace ConsoleHelloWorldServiceClient
{
class Program
{
static void Main(string[] args)
{
var adrs = new Uri[1];
adrs[0] = new Uri("http://localhost:6464");
using (ServiceHost host = new ServiceHost(typeof(HelloWorld.HelloWorldService),adrs))
{
host.Open();
Console.WriteLine("Server is open");
Console.WriteLine("Press Enter to close server");
Console.ReadLine();
}
}
}
}
世界,你好接口
namespace HelloWorld
{
[ServiceContract]
public interface IHelloWorldService
{
[OperationContract]
string SayHello();
}
}
你好世界級
namespace HelloWorld
{
[DataContract]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class HelloWorldService : IHelloWorldService
{
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "SayHello")]
public string SayHello()
{
return "Hello World!";
}
}
}
現在在我的HTML頁面我想點擊一個按鈕並顯示文字。
然後使用jQuery與服務進行通信:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript"
src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.1.min.js">
</script>
<script type="text/javascript">
var url = 'http://localhost:6464/HelloWorldService';
$(document).ready(function() {
$("#get").click(function() {
var urlGet = url + 'SayHello';
$.getJSON(urlGet, function (data) {
$('#text').val(data);
});
});
});
</script>
</head>
<body>
<input id="text" type="text" value="Hello" />
<input id="get" type="button" value="Get" />
</body>
</html>
但我的感覺是,只針對Web服務器... 我怎樣才能做到這一點這個客戶用的?
感謝您的幫助。
非常感謝您的意見。我會更正我的代碼並回復你。 :) – lla
請注意 - 對於WCF端點來說「JSON」,你還需要添加'WebHttpBehavior':host.AddServiceEndpoint(typeof(IHelloWorldService),new WebHttpBinding(),「」).Behaviors.Add (新WebHttpBehavior());' – carlosfigueira
@carlosfigueira好抓!我完全錯過了它。我會更新答案。 – vendettamit