[英]Can't send a stream file with httpClient to web api
我試圖將C#中的集成測試項目中的基本文件發送到Web api。 但是我不知道為什么,每一次電話我都會得到一個例外。
Json.JsonSerializationException:從“ System.Io.FileStream”上的“ ReadTimeout”獲取值時出錯
我發現無法讀取此屬性,所以也許這就是為什么我的httpclient無法序列化它的原因。 那么如何將文件發送到Web API?
這是我來自客戶端的代碼:
using (StreamReader reader = File.OpenText("SaveMe.xml"))
{
response = await client.PostAsJsonAsync($"api/registration/test/", reader.BaseStream);
response.EnsureSuccessStatusCode();
}
而我的控制器:
[Route("api/registration")]
public class RegistrationController : Controller
{
[HttpPost, Route("test/")]
public ActionResult AddDoc(Stream uploadedFile)
{
if (uploadedFile != null)
{
return this.Ok();
}
else
{
return this.NotFound();
}
}
我不確定他們是否仍然在.NET Core中支持PostAsJsonAsync
。 因此,我決定使用PostAsync
如下重寫您的代碼段:
using (StreamReader reader = File.OpenText("SaveMe.xml"))
{
var response = await client.PostAsync($"api/registration/test/", new StreamContent(reader.BaseStream));
}
更新您的API方法,使其看起來像:
[Route("api/registration")]
public class RegistrationController : Controller
{
[HttpPost, Route("test/")]
public ActionResult AddDoc()
{
//Get the stream from body
var stream = Request.Body;
//Do something with stream
}
首先,您必須從文件讀取所有數據,然后再發送。 要打開.xml
文件,請使用XmlReader
。 看這里在C#中使用XmlReader讀取Xml
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.