MVC, WCF ASP.NET 4.0 & JQUERY -
i've spent past few days getting frustrated wcf, i've decided post on here because.. well.. don't have clue start!.. appreciated!
firstly: when creating wcf service in .net 4.0, template should use if want able create service accept data ajax post using jquery? (i'd able have global.asax if possible).
secondly: service works fine in wcf test client, when manage accept requests, test client stops showing service methods. post methods seem refuse work outright.
i'd develop wcf service run on iis server can hook 1 of applications via jquery ajax call.
if has tutorial point's me in right direction, appreciated havn't been able find on wcf using .net 4, works.
cheers
the first thing should consider same origin policy restriction. if not able comply , web service not hosted on same domain consuming ajax script may stop reading answer here , rethink architecture.
if still reading start defining service contract , implementation usual:
[servicecontract] public interface ifoo { [operationcontract] string getdata(int value); } public class fooservice : ifoo { public string getdata(int value) { return string.format("you entered: {0}", value); } }
then add fooservice.svc
file expose service in iis:
<%@ servicehost language="c#" debug="true" service="somens.fooservice" codebehind="fooservice.svc.cs" factory="system.servicemodel.activation.webscriptservicehostfactory" %>
the last line factory="system.servicemodel.activation.webscriptservicehostfactory"
extremely important allow use json.
the last part web.config:
<system.servicemodel> <behaviors> <servicebehaviors> <behavior> <servicemetadata httpgetenabled="true"/> <servicedebug includeexceptiondetailinfaults="false"/> </behavior> </servicebehaviors> </behaviors> <servicehostingenvironment multiplesitebindingsenabled="true" /> </system.servicemodel>
and html page sending ajax request consume service:
<!doctype html> <html> <head> <title>wcf test</title> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" src="http://www.json.org/json2.js"></script> <script type="text/javascript"> $(function () { $.ajax({ // notice url here: need hosted on same domain url: '/fooservice.svc/getdata', type: 'post', contenttype: 'application/json; charset=utf-8', data: json.stringify({ value: 7 }), success: function (result) { alert(result.d); } }); }); </script> </head> <body> </body> </html>
Comments
Post a Comment