0

I have searched for a good example or explanation but couldn´t find anything helpful.

I have an ApiController TestController Where I have a Post function

public void Post([FromBody] string value)
{
//something
}

What would I have to do to send a simple string like "test" from a WinForms App to this function? Note: My Problem is not to hit the function that works fine in many different ways. The Problem is that the value is always null.

JJJJ
  • 73
  • 1
  • 9
  • my guess you need to post string content to api? i'm right. – Jagadeesh Govindaraj Jun 24 '15 at 10:01
  • http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client – Hamid Pourjam Jun 24 '15 at 10:01
  • 2
    possible duplicate of [POST a string to Web API controller in ASP.NET 4.5 and VS 2012 RC](http://stackoverflow.com/questions/11662064/post-a-string-to-web-api-controller-in-asp-net-4-5-and-vs-2012-rc) – Oliver Gray Jun 24 '15 at 10:05
  • Is your question about the routing e.g. how to determine the url to post to? Or the actual way of posting a string to a web resource? – rdoubleui Jun 24 '15 at 10:22
  • the routing is working, and when insted of [FromBody] string, my parameter is a httpRequestMessage everything works perfectly fine. but I would prefer a string parameter. – JJJJ Jun 24 '15 at 10:46
  • What does your `HttpConfiguration` look like? – rdoubleui Jun 24 '15 at 10:47
  • @rdoubleui what do you mean? – JJJJ Jun 24 '15 at 10:49
  • Extend the question with the configuration that you pass into the `AppBuilder` with which you start the `WebApp`. There you'll have options to what media types are being supported. – rdoubleui Jun 24 '15 at 10:51
  • I don´t see that in my application – JJJJ Jun 24 '15 at 10:58
  • Is it self-hosted? How do you start the controller? – rdoubleui Jun 24 '15 at 11:03
  • not self hosted two different applications. I start them both manually – JJJJ Jun 24 '15 at 11:10
  • At some point in your code you will set the routes. There you'll be able to set the media types as stated below. You already came to a `HTTP 415` indicating that this is the only thing that's missing. Post more code of the process holding the api service and we might be able to provide help. – rdoubleui Jun 24 '15 at 11:18

3 Answers3

0

I use the following which works fine for me.

// Create a WebRequest to the remote site
WebRequest myWebClient = WebRequest.Create(uri);
myWebClient.ContentType = "application/xml";
myWebClient.Method = method;

// Apply ASCII Encoding to obtain the string as a byte array.
string postData = //Data you want to post;
byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(postData);
Stream dataStream = myWebClient.GetRequestStream();

dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();

// Call the remote site, and parse the data in a response object
System.Net.WebResponse response = myWebClient.GetResponse();
// Check if the response is OK (status code 200)

//if (response.StatusCode == System.Net.HttpStatusCode.OK)
//{
// Parse the contents from the response to a stream object
System.IO.Stream stream = response.GetResponseStream();
// Create a reader for the stream object
System.IO.StreamReader reader = new System.IO.StreamReader(stream);
// Read from the stream object using the reader, put the contents in a string
string contents = reader.ReadToEnd();

This will serialize object into xml if you want to post an object.

 public string ToXml(object Obj, System.Type ObjType)
 {
     XmlSerializer ser = default(XmlSerializer);
     ser = new XmlSerializer(ObjType);

     MemoryStream memStream = default(MemoryStream);
     memStream = new MemoryStream();

     XmlTextWriter xmlWriter = default(XmlTextWriter);
     xmlWriter = new XmlTextWriter(memStream, Encoding.UTF8);
     xmlWriter.Namespaces = true;
     ser.Serialize(xmlWriter, Obj);
     xmlWriter.Close();
     memStream.Close();

     string xml = null;
     xml = Encoding.UTF8.GetString(memStream.GetBuffer());
     xml = xml.Substring(xml.IndexOf(Convert.ToChar(60)));
     xml = xml.Substring(0, (xml.LastIndexOf(Convert.ToChar(62)) + 1));

     return xml;

 }
Gericke
  • 2,109
  • 9
  • 42
  • 71
0

Most basic tasks can be accomplished quite easily with WebClient:

using (var wc = new WebClient()) 
{
    wc.Headers.Add("Content-Type", "application/json");
    var response = wc.UploadString("http://provide-url", "\"test\"");
}

EDIT: Turns out you'll need to specify the Content-Type in the client as application/json AND wrap the string in additional quotes.

According to this post, it has to do with the way Web API handles parameter binding.

Community
  • 1
  • 1
rdoubleui
  • 3,554
  • 4
  • 30
  • 51
  • when I do this I get an WebExeption (415) Unsupported Media Type – JJJJ Jun 24 '15 at 10:44
  • The media type is missing and needs to be specified in the config, please see my edit. – rdoubleui Jun 24 '15 at 10:56
  • when I do this with text/plain I get the same error. when I use z.B. application/xml I hit the function but the param is null – JJJJ Jun 24 '15 at 11:31
  • Can you verify with a basic sample that you're not accidentally having a different route processing the case where you don't hit the method? – rdoubleui Jun 24 '15 at 11:35
  • I basiclly did it like above... the route is fine that is not the problem. I think the problem is that the param is a string and the param binding is not working but I have no idea how to fix that. – JJJJ Jun 24 '15 at 11:40
  • Have you tried to do the post with another rest client to see if your client code is the problem? – rdoubleui Jun 24 '15 at 11:42
0

Try to use HttpClient from System.Net.Http.dll:

using (var loClient = new HttpClient() { BaseAddress = new Uri("http://localhost:55743/") })
{
    var loResult = loClient.PostAsJsonAsync<string>("api/Test/Post/", "Hello World");
    loResult.Result.EnsureSuccessStatusCode();
}
PinBack
  • 2,499
  • 12
  • 16