Reputation: 2573
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?
Upvotes: 3
Views: 5167
Reputation: 10099
I was running into the same problem. Sometimes POST-ing JSON works, but not always. It's unreliable and the reasons for it failing can be mysterious. I ended finding that POST was more work than it's worth, and that you could accomplish the same with GET. If you don't absolutely have to design your service with POST, I have a working example of how to accomplish what you're trying to do with POST with GET here:
http://winsockwebsocket.codeplex.com/
(It's part of a seemingly unrelated project, but just go to the Northwind.Web folder to see a complete working example of send/receving JSON from jQuery to WCF.)
Upvotes: 0
Reputation: 5374
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.
Upvotes: 1
Reputation: 32950
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?
Upvotes: 2