I have created a WCF service and it is hosted in windows service. When I have added a web reference to that service to an asp.net web forms project through right client menu in the solution explorer I am able to access the service and add reference to it.
Now I want to access this service through AJAX client (i.e in ASP.NET project through ScriptManager component)and call the service in a timer to get continuous stream of values.
I have never worked on AJAX or web that much, I did not find an suitable example on net on this.
I'm using WSHttpBinding.
I'm posting my code so that you can tell where I'm doing wrong.
WCF Service Library Code:
ITestService.cs code....
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
namespace TestServiceLibrary
{
// NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in App.config.
[ServiceContract(Namespace="TestServiceLibrary")]
public interface ITestService
{
[OperationContract]
[WebGet]
double Add(double n1, double n2);
// TODO: Add your service operations here
}
}
TestService.cs code...............
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace TestServiceLibrary
{
// NOTE: If you change the class name "Service1" here, you must also update the reference to "Service1" in App.config.
public class TestService : ITestService
{
public double Add(double n1, double n2)
{
return n1 + n2;
}
}
}
TestServiceHost.cs (code of console application)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using TestServiceLibrary;
namespace TestServiceHost
{
class Program
{
static void Main(string[] args)
{
ServiceHost myhost = new ServiceHost(typeof(TestService));
myhost.Open();
while (System.Console.ReadKey().Key != System.ConsoleKey.Enter)
{
//System.Threading.Thread.Sleep(100);
}
myhost.Close();
}
}
}
XML Configuration of app.config... same in both wcf service library and wcf service host(console application in this case..)
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<compilation debug="true" />
</system.web>
<!-- When deploying the service library project, the content of the config file must be added to the host's
app.config file. System.Configuration does not support config files for libraries. -->
<system.serviceModel>
<services>
<service name="TestServiceLibrary.TestService" behaviorConfiguration="TestServiceLibrary.Service1Behavior">
<host>
<baseAddresses>
<add baseAddress = "http://localhost:8731/TestServiceLibrary/TestService/" />
</baseAddresses>
</host>
<!-- Service Endpoints -->
<!-- Unless fully qualified, address is relative to base address supplied above -->
<endpoint name="TestService_wsHttpBinding" address ="" binding="wsHttpBinding" contract="TestServiceLibrary.ITestService">
<!--
Upon deployment, the following identity element should be removed or replaced to reflect the
identity under which the deployed service runs. If removed, WCF will infer an appropriate identity
automatically.
-->
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<!-- Metadata Endpoints -->
<!-- The Metadata Exchange endpoint is used by the service to describe itself to clients. -->
<!-- This endpoint does not use a secure binding and should be secured or removed before deployment -->
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="TestServiceLibrary.Service1Behavior">
<!-- To avoid disclosing metadata information,
set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="True"/>
<!-- To receive exception details in faults for debugging purposes,
set the value below to true. Set to false before deployment
to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
Web Client (asp.net client, default.aspx) code...
<!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>
<title>Simple AJAX Service Client Page</title>
<script type="text/javascript">
// <![CDATA[
// This function creates an asynchronous call to the service
function makeCall(operation){
var n1 = document.getElementById("num1").value;
var n2 = document.getElementById("num2").value;
// If user filled out these fields, call the service
if(n1 && n2){
// Instantiate a service proxy
var proxy = new TestServiceLibrary.ITestService();
// Call correct operation on proxy
switch(operation){
case "Add":
proxy.Add(parseFloat(n1), parseFloat(n2), onSuccess, onFail, null);
break;
}
}
}
// This function is called when the result from the service call is received
function onSuccess(mathResult){
document.getElementById("result").value = mathResult;
}
// This function is called if the service call fails
function onFail(){
document.getElementById("result").value = "Error";
}
// ]]>
</script>
</head>
<body>
<h1>
Simple AJAX Service Client Page</h1>
<p>
First Number:
<input type="text" id="num1" /></p>
<p>
Second Number:
<input type="text" id="num2" /></p>
<input id="btnAdd" type="button" onclick="return makeCall('Add');" value="Add" />
<p>
Result:
<input type="text" id="result" /></p>
<form id="mathForm" action="" runat="server">
<asp:ScriptManager ID="ScriptManage开发者_如何转开发r" runat="server">
<Services>
<asp:ServiceReference Path="http://localhost:8732/TestServiceLibrary/TestService/" />
</Services>
</asp:ScriptManager>
</form>
</body>
</html>
The error Im getting when accessing the webservice through asp.net in ajax is Microsoft JScript runtime error: 'TestServiceLibrary' is undefined
Please go through this code and help me in finding the problem. Thank you all for your responses.
Looks like the problem is with my service hosting and the endpoint i'm using.
I should modified my service hosting in the console application to use WebServiceHost instead of ServiceHost, then only the ajax clients can talk to my service. Instead of wsHttpBinding, I should use webHttpBinding.
So the code for webHosting is as follows.
using (var host = new WebServiceHost(
typeof(TestService)))
{
// Start listening for messages
host.Open();
Console.WriteLine("Press any key to stop the service.");
Console.ReadKey();
// Close the service
host.Close();
}
The xml configuration of my console is
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.serviceModel>
<services>
<service
name="TestServiceLibrary.TestService"
behaviorConfiguration="">
<endpoint address="http://localhost:8732/TestService"
binding="webHttpBinding"
bindingConfiguration=""
name="TestService_WebHttp"
contract="TestServiceLibrary.ITestService" />
</service>
</services>
</system.serviceModel>
</configuration>
Now when I did this changes I'm able to call my service through ie using the following url in ie http://localhost:8732/TestService/Add?n1=20&n2=20 and result returned by it is as follows <double xmlns="http://schemas.microsoft.com/2003/10/Serialization/">40</double>
Finally i found the solution to my problem. Im using JSON as way of communicating data and the script for receiving the data is as follows:
<script type="text/javascript">
$("#mybutton").click(function () {
$.getJSON("http://localhost:8732/TestService/Add", null, function (result) {
});
});
</script>
Use some tool like firebug to determine what is happening with the request. WSHttpBinding is secure by default. Check your security settings. Try first with no security to make sure it is not a security issue.
Have you attempted to connect to the service from the AJAX client yet? If so, are you getting any errors?
Without seeing code, there could be a number of things as Chandermani has said.
I've not done AJAX with WCF, but looking over the article Preet recommended, I would suggest checking (if you haven't already) that your AJAX client has the necessary code as per the article.
Are your service operations decorated with [WebGet]?
Do you have the config file for the AJAX client set up properly? Is the service's config file set up properly?
精彩评论