无法用httpClient发送流文件到web api

问题描述:

我试图从C#中的集成测试项目发送基本文件到web api。 但我不知道为什么,每次打电话我都会遇到异常。无法用httpClient发送流文件到web api

Json.JsonSerializationException:从“ReadTimeout”上“System.Io.FileStream”

我发现这个属性不能被读取,所以也许就是为什么我的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(); 
      } 

     } 

下面的截图中我们可以看到,房地产[ReadTimeout]不能访问。 enter image description here

+0

我怀疑你不能使用'FileStream'。您也可以检查此:https://*.com/questions/10320232/how-to-accept-a-file-post – Subbu

+0

好吧,我会检查今晚 –

+0

对不起,但我无法找到你的帮助链接:-(不解释如何发送文件与httpCLient,顺便说一句,我更新我的帖子。我的控制器等待一个[流]而不是[FileStream] –

我不确定他们是否仍然支持我在.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。看看Reading Xml with XmlReader in C#

+0

如果我尝试使用(文本文件),问题仍然存在 –