gpt4 book ai didi

c# - 远程服务器返回错误 : (415) Unsupported Media Type

转载 作者:太空狗 更新时间:2023-10-29 19:53:44 28 4
gpt4 key购买 nike

我尝试将文本文件从 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);
}

所以..在客户端代码下我遇到了那个异常

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

知道我遗漏了什么吗?

最佳答案

您正在设置 ContentType = "text/plain",此设置驱动格式化程序选择。请查看Media Formatters了解更多详情。

摘录:

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

因此,没有内置的文本/纯文本格式化程序,即:不支持的媒体类型。您可以将内容类型更改为某些支持的、内置的或实现自定义类型(如 link 中所述)

关于c# - 远程服务器返回错误 : (415) Unsupported Media Type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20909118/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com