Thursday 21 January 2010

WCF RESTful Services AJAX-enabled

http://www.west-wind.com/WebLog/posts/310747.aspx



UriTemplate:


Create a RESTful WCF Service:

1) Set WebGet or WebInvoke

[OperationContract]
[WebGet(UriTemplate = "Add?a={a}&b={b}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
int TestAdd(int a, int b);

2) Add <webHttp/> endpoint behavior

<endpointBehaviors> <behavior name="VMServiceEndpointBehavior"> <webHttp/> </behavior> </endpointBehaviors>

3) Access the service

http://localhost:4082/MyApp.WebUI/Services/VMService.svc/Add?a=1&b=2

Example2:

1) Define your service

[OperationContract]
[WebInvoke(Method = "POST" , UriTemplate = "Add", RequestFormat = WebMessageFormat.Json ,
ResponseFormat = WebMessageFormat.Json)]
int TestAdd(int a, int b);

2) Create a proxy class
function serviceProxy(serviceUrl) {
var _I = this;
this.serviceUrl = serviceUrl;
this.invokeJsonMethod = function(method, dataInJson, succeededCallback, failedCallback) {
var url = _I.serviceUrl + method;
$.ajax({
type: "POST",
url: url,
data: dataInJson,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
if (succeededCallback != null)
succeededCallback(result);
},
error: function(result) {
if (failedCallback != null)
failedCallback(result);
}
});
}
}

3) Call the service

function btnTestAdd_click() {
var url = "http://localhost/AppName/Services/VMService.svc/";
var proxy = new serviceProxy(url);
var methodName = "Add";
var params = '{"a":1,"b":2}';
proxy.invokeJsonMethod(methodName, params, succeeded, failed);
}

function succeeded(e) {
//debugger;
alert(e.TestAddResult);
}

function failed(e) {
// debugger;
alert(e);
}

General Tips:
  • Parameter's Location: If you're using GET verb, it means that the parameters of the method must appear in the url using a UriTemplate, whereas when using other verbs (POST, DELETE, PUT), the parameters can appear in the body section of the message not url.
  • GET Parameter's Type: If you're using GET verb, it means that the parameters of the method must be of type 'string'. Which means that if you need other types of parameters such as int you must use POST verb. However the output parameter can be of any type as long as it is serializable.
  • WebMessageBodyStyle: The default option for WebMessageBodyStyle is Bare which means both Responses and Requests are not wrapped.
  • WebMessageFormat: The default data format for the webHttp behavior is XML, while the default data format for the enableWebScript behavior is JSON.
  • <webHttp>: This element specifies the WebHttpBehavior on an endpoint through configuration. This behavior, when used in conjunction with the <webHttpBinding> standard binding, enables the Web programming model (REST) for a WCF service.
  • <enableWebScript />: This element enables the endpoint behavior that makes it possible to consume the service from ASP.NET AJAX web pages.

No comments: