I want in C# to call an ApiController also in C# but I'm getting error 415 or 400 when uploading the Json using the UploadString method from the WebClient instance.
The server code is the auto-generated call TestController. The file is exactly how Visual Studio 2019 generate it.
[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
// GET: api/Test
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// POST: api/Test
[HttpPost]
public void Post([FromBody] string value)
{
}
...
}
The client code look like that:
WebClient client = new WebClient();
client.UploadString("https://localhost:44345/api/Test", "ABC"); // Edit: "ABC" is not a valid JSON
I'm getting System.Net.WebException: 'The remote server returned an error: (415) Unsupported Media Type.'
So after googling, most suggest is the ContentType not getting specify, if I add
client.Headers[HttpRequestHeader.ContentType] = "application/json";
I get System.Net.WebException: 'The remote server returned an error: (400) Bad Request.'
Any clue?
Seems like the problem is related to the POST
/PUT
/PATCH
... if I do the GET
, it's working and returning me the sample data ["value1","value2"]
Edit: I'm not stick to using WebClient.UploadString method but I would like a solution that doesn't involved 25 lines of custom code... I means I can't believe it's that hard where you can do it in jQuery using a single line.