Click here to Skip to main content
15,886,788 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I get a HTTP error 415 Unsupported Media Type in the HttpResponseMessage.
How do I get the server side codes to work?

HTTPClient is used to post byte array data as follow...

using(HttpClient c=new HttpClient()
{
c.DefaultRequestHeader.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream)

byte[] Data=new byte { 0x00, 0x01, 0x02... };

HttpResponseMessage r=await c.PostAsync("http://abc.com/api/File/Filename", new ByteArrayContent(Data);

if(r.IssuccessStatusCode) return true;
return false;
}

Server Side(MVC/Razor) receive byte array as follow

[HttpPost("{Filename}")]
public async Task<int> Post([FromBody] string Filename)
{
MemoryStream ms=new MemoryStream((int)Request.Body.Length);
await Request.Body.CopyToAsync(ms);

byte[] b=ms.ToArray(); ms.close();
File.WriteAllBytesAsync("Data.bin", b);
return b.Length;
}

What I have tried:

Compiled under Visual Studio 2017 running on Windows 10 Pro workstation
Posted
Updated 23-Jan-19 5:53am
Comments
Member 8921416 23-Jan-19 3:20am    
I've seen that example and didn't see useful code snippets on server side.
The client side is straight forward using HttpClient. Server side seems to even crash at Request.Body.Length accessor
Richard Deeming 24-Jan-19 8:05am    
Why are you binding the Filename parameter to both the route and the request body, whilst also trying to read the request body manually?

Also, setting the "accept" header on the request tells the server which response formats it can send. It doesn't change which request formats the server will accept.

1 solution

You can do it as simply as this
C#
[HttpPost]
public void Post(byte[] bytes)
{
   //your code
}

Web API handles byte array as input parameters quite well
 
Share this answer
 
Comments
Member 8921416 23-Jan-19 19:49pm    
HttpClient.PostAsyn(string URL, HttpContent c) doesn't allow the byte array to be pass via URL. How HttpClient is going to call this API at server side?
Bohdan Stupak 26-Jan-19 11:14am    
Unlike GET request you don't pass POST request parameters via URL. You pass them via body. Have a look at the example https://stackoverflow.com/questions/16416601/c-sharp-httpclient-4-5-multipart-form-data-upload
Member 8921416 28-Jan-19 4:06am    
if HttpClient is used to simply post a ByteArrayContent, the server side should be able to pickup the ByteArrayContent from the HttpRequest body. I'm looking for sample code that allow server side to collect the ByteArrayContent posted by client.
Bohdan Stupak 31-Jan-19 5:50am    
try this one https://stackoverflow.com/a/23884972

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900