The remote server responded with an error: (415) Unsupported media type

I am trying to upload a text file from a WPF RESTful client to an ASP.NET MVC WebAPI 2 website .

Client code

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost:22678/api/Account/UploadFile?fileName=test.txt&description=MyDesc1"); request.Method = WebRequestMethods.Http.Post; request.Headers.Add("Authorization", "Bearer " + tokenModel.ExternalAccessToken); request.ContentType = "text/plain"; request.MediaType = "text/plain"; byte[] fileToSend = File.ReadAllBytes(@"E:\test.txt"); request.ContentLength = fileToSend.Length; using (Stream requestStream = request.GetRequestStream()) { // Send the file as body request. requestStream.Write(fileToSend, 0, fileToSend.Length); requestStream.Close(); } using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) Console.WriteLine("HTTP/{0} {1} {2}", response.ProtocolVersion, (int)response.StatusCode, response.StatusDescription); 

WebAPI 2 Code

 [HttpPost] [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)] [Route("UploadFile")] public void UploadFile(string fileName, string description, Stream fileContents) { byte[] buffer = new byte[32768]; MemoryStream ms = new MemoryStream(); int bytesRead, totalBytesRead = 0; do { bytesRead = fileContents.Read(buffer, 0, buffer.Length); totalBytesRead += bytesRead; ms.Write(buffer, 0, bytesRead); } while (bytesRead > 0); var data = ms.ToArray() ; ms.Close(); Debug.WriteLine("Uploaded file {0} with {1} bytes", fileName, totalBytesRead); } 

So .. Under the client code, I came across this exception

The remote server returned an error: (415) Unsupported media type.

Any clue what I'm missing?

+7
c # asp.net-web-api
source share
2 answers

+1 about what was mentioned above in Radim ... According to your action, binding the web API model, the fileContents parameter is a complex type and, by default, involves reading the contents of the request body using formatters. (note that since the fileName and description parameters are of type string , they are expected to come from uri by default).

To prevent model binding, you can do something like the following:

 [HttpPost] [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)] [Route("UploadFile")] public async Task UploadFile(string fileName, string description) { byte[] fileContents = await Request.Content.ReadAsByteArrayAsync(); .... } 

By the way, what do you plan to do with this fileContents ? Are you trying to create a local file? if so, is there a better way to handle this.

Update based on your last comment :

A quick example of what you could do

 [HttpPost] [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)] [Route("UploadFile")] public async Task UploadFile(string fileName, string description) { Stream requestStream = await Request.Content.ReadAsStreamAsync(); //TODO: Following are some cases you might need to handle //1. if there is already a file with the same name in the folder //2. by default, request content is buffered and so if large files are uploaded // then the request buffer policy needs to be changed to be non-buffered to imporve memory usage //3. if exception happens while copying contents to a file using(FileStream fileStream = File.Create(@"C:\UploadedFiles\" + fileName)) { await requestStream.CopyToAsync(fileStream); } // you need not close the request stream as Web API would take care of it } 
+5
source share

You set ContentType = "text/plain" , and these settings lead to the choice of formatting. See Media Formatters for more information .

Exposure:

In the Web API, the media type determines how the Web API serializes and deserializes the body of the HTTP message. There is built-in support for XML, JSON, as well as data with urlencoded forms, and you can support additional media types by writing a media format.

Thus, there is no built-in text / simple formatting, i.e.: Unsupported media type. You can change the content type to some supported, built-in or implement custome (as described in the link )

+13
source share

All Articles