簡體   English   中英

遠程服務器返回錯誤:(415)不支持的媒體類型

[英]The remote server returned an error: (415) Unsupported Media Type

我嘗試將文本文件從WPF RESTful客戶端上載到ASP.NET MVC WebAPI 2網站

客戶代碼

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代碼

[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);
}

所以..在客戶端代碼下,我面臨那個異常

遠程服務器返回錯誤:(415)不支持的媒體類型。

任何線索我想念什么?

您正在設置ContentType = "text/plain" ,並且此設置將驅動Formatter選擇。 請檢查媒體格式化程序以獲取更多詳細信息。

摘錄:

在Web API中,媒體類型確定Web API如何序列化和反序列化HTTP消息正文。 內置支持XML,JSON和表單編碼的數據,您可以通過編寫媒體格式化程序來支持其他媒體類型。

因此,沒有內置的文本/普通格式器,即: 不支持的媒體類型 您可以將content-type更改為某些受支持的內置類型,或實現custome one(如鏈接中所述)。

上面Radim提到的內容+1 ...根據您的操作,Web API模型綁定會注意到參數fileContents是復雜類型,默認情況下假定使用格式器讀取請求正文內容。 (請注意,由於fileNamedescription參數是string類型,因此默認情況下它們應來自uri)。

您可以執行以下操作來防止模型綁定發生:

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

   ....
}

順便說一句,您打算如何處理這個fileContents 您是否要創建本地文件? 如果是,則有更好的方法來處理此問題。

根據您的最新評論進行更新

您可以做什么的簡單示例

[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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM