tags:

views:

964

answers:

2

I'm new to WCF (and pretty rusty with .NET in general) so there's a distinct chance this is an answered question and I just missed it.

I'm building an ASP.NET MVC app that will be using a RESTful JSON-based API for its backend. I've been looking into the different options for how to talk to such an API in .NET and it looks like WCF is the most popular choice by far. Reading into WCF some more I now have a basic consumer class that makes a request, which is a start.

But now I need to do more with it, and I'm not making much headway. I need to send a POST to the API with a JSON body. Here's what I have so far:

using System.ServiceModel;
using System.ServiceModel.Web;
using System.Runtime.Serialization;

namespace APIConsumer {
    [ServiceContract]
    public interface IAPIClient {
        [OperationContract]
        [WebInvoke(
            Method = "POST",
            BodyStyle = WebMessageBodyStyle.Bare,
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
            UriTemplate = "/session/login.json"
            )]
        string SessionLogin(string login_name);
    }

    public class APIClient : ClientBase<IAPIClient>, IAPIClient {
        public string SessionLogin(string login_name) {
            return this.Channel.SessionLogin(login_name);
        }
    }
}

What I can't figure out is the correct way to pass a) ANY data within the POST body & b) a proper serialized .NET object as JSON in the POST body. Is there a good example of how to work that out there somewhere?

+1  A: 

If you are wondering how to format the JSON body of your POST to the operation SessionLogin, in your case, it would be very simple. The JSON data would just be:

{"login_name": "someuser"}

The WCF framework will handle mapping that data to your operation, and will pass the value "someuser" to the parameter login_name for you. Is this what you needed, or was there a more complex scenario you needed help with?

jrista
The format of the JSON isn't the issue, but how would I make sure the JSON actually gets sent with the request in the body?
Tivac
That would depend on how your calling the service. Is it via javascript, jquery, mootools? Or is it from a .NET client? If its from jquery, its pretty easy, as jquery provides a handy ajax caller that has a data parameter (goes in the body). If its another .NET client, you don't even need to bother with json notation at all. You work directly with native objects, and WCF handels all the serialization and translation for you.
jrista
A: 

Take a look at How to: Serialize and Deserialize JSON Data article on MSDN. You also need to make sure to set the content-type in your request to 'application/json' on the client side. Check out this SO question.

Mehmet Aras