0

I have been working through the new WebAPI over on the asp.net site. I've created a few samples using simple strings that I can GET. I am looking to see if I can now POST and PUT to the service.

I am looking to see how I should add an object to the request that I can then POST or PUT from a .net 3.5 console application. The object I am trying to send is just a simple User class with Name, Surname, and UserID.

From my testing it seems that I can serialize this and send it via the URI but that hardly seems correct. I notice that these requests have headers, can I put the data in there?

deanvmc
  • 5,957
  • 6
  • 38
  • 68

2 Answers2

4

Using .NET 3.5, there are not many elegant options I think but this code using WebClient works (you need adding reference to System.Web.Extensions):

WebClient client = new WebClient();
JavaScriptSerializer serializer = new JavaScriptSerializer();
var data = serializer.Serialize(new {Name = "Ali", Title = "Ostad"});
client.Headers[HttpRequestHeader.ContentType] = "application/json";
var downloadString = client.UploadString("http://localhost:59174/api/values", data); // value is "Ali"

And here is controller action:

// POST /api/values
public string Post(JsonValue value)
{
    return value.AsDynamic().Name;
}
Aliostad
  • 80,612
  • 21
  • 160
  • 208
1

Check out the HttpClient on NuGet. This makes it easy to do most things over http.

And here's an example of using it.

Ben Foster
  • 34,340
  • 40
  • 176
  • 285
  • Does this client work with .net 3.5 (Winforms / Console / WPF / Silverlight) ? – deanvmc Apr 27 '12 at 08:47
  • As far as I know the HttpClient (part of WCF Web Api) is .NET 4 but an older build is available for .net 3.5 - see http://stackoverflow.com/questions/8257652/webapi-httpclient-for-net-framework-3-5 – Ben Foster Apr 27 '12 at 22:18