Wednesday, November 10, 2010

.NET WCF Service and ASP.NET Service with JSON

Some month back I wanted to create a simple .NET webservice which was called from JQuery, more precisely via JSON.

By that time, WCF was not a new technology any more: It was already well established and of course my thought was, I will use this technology for creating the service.

This webservice had only one simple usage: it should write some values into a Database so the signature of the Method looked something like this:

public void AddToDb(string value)

What I did for the WCF-Service then was the usual you do when creating this kind of service:
  • Creating and Implementing the ServiceContract
  • Creating and Implementing the OperationContracts
  • Adapting the web.config

and after that, the Service just worked fine. At least for SOAP.

For making this able to be called via JSON, I needed also the adapt some attributes of the ServiceMethods and adapt the web.config section.

[WebInvoke(BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json)]
public void AddToDb(string value)

<endpoint contract="MyServiceContract"
binding="webHttpBinding" 
behaviorConfiguration="AjaxBehavior" />

After all this configuration, it didn't work and I couldn't figure out why. It still worked fine for SOAP, but unfortunately that's not what I needed. I tried for some time, but fortunately my patience run out some when.

What did I do now? I switched back to the good old Asp.NET webservice. The Method of course kept it's signature and implementation but I threw away all the configuration and attributes needed for WCF. So the Method finally looked like

[WebMethod]
public void AddToSession(string value)

Than I started to search around on how to make this usable via JSON and I was very surprised after some time: You don't need to do anything! It's completely out of the box.

So I just created the JQuery-Code needed for calling the Method and I finished it.

var parameters = "{'value':'somevaluetosave'}";
$.ajax({
    url: "/Service.asmx/AddToDb",
    data: parameters,
    type: "POST",
    async: true,
    contentType: "application/json; charset=utf-8",
    processData: false,
    dataType: "json",
    success: function (msg) {

        if (msg.d == 'success') {
            alert('Everything went fine');
        }

        else {
            alert('Not what I wanted');
        }
    }
});

Conclusion

Maybe WCF is more advanced, more modern and the the new guy in town, but when your requirements are simple, try to keep the code also simple!

New technology is nice, and I really enjoy using WCF for other projects: but sometimes you just get too much overhead with it and especially then you should think about what you need and not what you fancy to use.

2 comments: