I have the following Web API method in an ApiController class:
public HttpResponseMessage Post([FromBody]byte[] incomingData) { ... }
I want incomingData
to be the raw content of the POST. But it seems that the Web API stack attempts to parse the incoming data with the JSON formatter, and this causes the following code on the client side to fail:
new WebClient().UploadData("http://localhost:15134/api/Foo", new byte[] { 1, 2, 3 });
Is there a simple workaround for this?
Create a Resource (HTTP POST) In this method set base address of Asp.Net Web API and sets the accept header to application/json that tells the server to send data in JSON Format. PostAsJsonAsyn:This method serializes object into JSON format and send POST request to. After that this method return Response object.
Using [FromBody] When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object). At most one parameter is allowed to read from the message body.
For anyone else running into this problem, the solution is to define the POST method with no parameters, and access the raw data via Request.Content
:
public HttpResponseMessage Post() { Request.Content.ReadAsByteArrayAsync()... ...
If you need the raw input in addition to the model parameter for easier access, you can use the following:
using (var contentStream = await this.Request.Content.ReadAsStreamAsync()) { contentStream.Seek(0, SeekOrigin.Begin); using (var sr = new StreamReader(contentStream)) { string rawContent = sr.ReadToEnd(); // use raw content here } }
The secret is using stream.Seek(0, SeekOrigin.Begin)
to reset the stream before trying to read the data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With