json - Communication between WCF (ServiceHost) and HTML (JQuery) -
i want program simple "hello world" example communication between wcf service , html page.
to program wcf server use code below:
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 open"); console.writeline("press enter close server"); console.readline(); } } } }
hello world interface
namespace helloworld { [servicecontract] public interface ihelloworldservice { [operationcontract] string sayhello(); } }
hello world class
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!"; } } }
now in html page click on button , display text.
then use jquery communicate service:
<!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>
but feeling client used webservers... how can it?
thanks help.
you missing couple of thing in hosting. there not bindings defined. specific connect jquery client service should available via http protocol , messages should in plain or understandable format i.e. json.
var adrs = new uri("http://localhost:6464"); using (servicehost host = new servicehost(typeof(helloworld.helloworldservice ),adrs)) { var restendpoint = host.addserviceendpoint(typeof(ihelloworldservice), new webhttpbinding(), ""); restendpoint.behaviors.add(new webhttpbehavior(); host.open(); console.writeline("server open"); console.writeline("press enter close server"); console.readline(); }
corrections in servicecontract declarations. webinvoke
attribute should on interface contract.
[servicecontract] public interface ihelloworldservice { [webinvoke(method = "get", responseformat = webmessageformat.json, uritemplate = "sayhello")] string sayhello(); }
your service goes like:
[servicebehavior(instancecontextmode = instancecontextmode.single)] public class helloworldservice : ihelloworldservice { public string sayhello() { return "hello world!"; } } }
the datacontract
should used on messages i.e. entities not on service.
Comments
Post a Comment