【问题标题】:Can't send a stream file with httpClient to web api无法使用 httpClient 将流文件发送到 Web api
【发布时间】:2017-07-10 13:20:02
【问题描述】:

我尝试将一个基本文件从我的 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();
            }

        }

这里我们可以看到截屏,属性[ReadTimeout]不能访问。

【问题讨论】:

  • 我怀疑你不能使用FileStream。您也可以查看:stackoverflow.com/questions/10320232/how-to-accept-a-file-post
  • 好的,我今晚会检查一下
  • 对不起,但我无法从您的链接中找到一些帮助 :-( 顺便说一下,没有解释如何使用 httpCLient 发送文件。我更新了我的帖子。我的控制器等待[Stream] 而不是 [FileStream]
  • @MehdiBugnard 确认您使用的是哪个版本的 asp.net-mvc。 asp.net-core 还是 asp.net-web-api?
  • 在我看来您正在发送 XML 并说它是 JSON。听起来好像不行。

标签: c# .net asp.net-web-api asp.net-web-api2 httpclient


【解决方案1】:

我不确定他们是否仍然支持 .NET Core 中的 PostAsJsonAsync,我正在使用它。所以我决定用PostAsync重写你的sn-p如下:

    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
    }

【讨论】:

    【解决方案2】:

    首先,您必须从文件中读取所有数据,然后再发送。要打开.xml 文件,请使用XmlReader。看这里Reading Xml with XmlReader in C#

    【讨论】:

    • 如果我尝试使用(文本文件)问题仍然存在
    猜你喜欢
    • 2018-08-10
    • 2019-05-10
    • 2016-10-02
    • 1970-01-01
    • 1970-01-01
    • 2017-06-09
    • 2012-05-11
    • 2018-11-21
    • 1970-01-01
    相关资源
    最近更新 更多