I have an Asp Net Core 2.1 application with a REST controller like this:
[Produces("application/json")]
[Route("api/Test")]
public class TestController : Controller
{
// GET: api/Test
[HttpGet]
public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; }
// GET: api/Test/5
[HttpGet("{id}", Name = "Get")]
public string Get(int id) { return "value"; }
// POST: api/Test
[HttpPost]
public void Post([FromBody]string value)
{
//.. testing code..
}
// PUT: api/Test/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value) {}
// DELETE: api/ApiWithActions/5
[HttpDelete("{id}")]
public void Delete(int id) {}
}
I'm trying to use "System.Net.HttpWebRequest" object to make a POST request to Rest controller.
In my client application, I have a method that receives data as a string.
The string content is a dynamic array of values such "param1=value1;param2=value2" (the number of elements is variable).
Can you help me to understand the correct way to send this data to the controller?
this is the code I'm trying to use in the client:
public static string PostWebApi(string postData)
{
var request = (HttpWebRequest)WebRequest.Create("http://localhost:64817/api/test");
// for example, assumes that postData value is "param1=value1;param2=value2"
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/json";
//request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream()) {
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
return responseString;
}
I'm using content type "application/json": if I try to use "application/x-www-form-urlencoded" I get "(415) Unsupported Media Type" error.
so... when I exec PostWebApi I receive a Null value parameter in the POST: api/Test method..
how can I receive the data I sent?
Thanks in advance.