远程服务器返回错误:(415)不支持的媒体类型 [英] The remote server returned an error: (415) Unsupported Media Type

查看:6933
本文介绍了远程服务器返回错误:(415)不支持的媒体类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着上传从 WPF REST风格的客户端ASP .NET MVC 2的WebAPI网站的文本文件

客户端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);
}

所以..在客户端code,我面临着异常

So.. Under the client code I am facing that exception

远程服务器返回错误:(415)不支持的媒体类型

The remote server returned an error: (415) Unsupported Media Type.

任何线索做什么我丢失?

Any clue what do I am missing?

推荐答案

+1什么拉迪姆了上面提到的......根据你的行动的Web API模型绑定通知的参数 fileContents 是一个复杂类型,默认情况下假设读取用格式化请求的主体内容。 (注意,由于文件名说明参数字符串类型,他们预计来自默认URI)。

+1 on what Radim has mentioned above...As per your action Web API model binding notices that the parameter fileContents is a complex type and by default assumes to read the request body content using the formatters. (note that since fileName and description parameters are of string type, they are expected to come from uri by default).

您可以不喜欢下面以prevent模型绑定发生:

You can do something like the following to prevent model binding to take place:

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

   ....
}

顺便说一句,你怎么打算这个做 fileContents ?你想创建一个本地文件?如果是的话,有一个更好的方式来处理这个问题。

BTW, what do you plan to do with this fileContents? are you trying to create a local file? if yes, there is a better way to handle this.

根据您最后的评论更新

你可以做一个简单的例子

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
}

这篇关于远程服务器返回错误:(415)不支持的媒体类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆