【问题标题】:Return Error code when file is not found in API call C#在 API 调用 C# 中找不到文件时返回错误代码
【发布时间】:2017-11-28 22:54:30
【问题描述】:

我正在尝试创建 API 调用以从 azure 数据湖存储 读取文件。但是,我无法分别针对找到和未找到的特定文件显示正确的响应和错误

我能够连接到 azure 数据湖并获取数据,正确使用 try-catch。请为c# API 提供正确的响应正文和响应代码。

try
        {
            string aa = GetItemInfo("/myfolder/subfolder/testfile.txt");
            return new string[]
            {
            "Hello",
            aa,
            "World"

        };
            }
catch {
            return new string[]
         {
            "Hello",
            "World"

     };

我的代码正在运行。由于我是 C# 上 API 调用的新手,因此我无法找出正确的方法。

【问题讨论】:

    标签: c# api azure asp.net-web-api


    【解决方案1】:

    您必须创建以下内容

    var responseMessage = new HttpResponseMessage>(errors, HttpStatusCode.BadRequest);

    抛出新的 HttpResponseException(responseMessage);

    你可以找到答案herehere

    【讨论】:

      【解决方案2】:

      有很多原因会导致异常。例如,网络问题或令牌已过期。为了显示找到和未找到的特定文件的正确响应和错误,我建议您在阅读项目信息之前检查路径是否存在。

      public static  bool ItemExist(string path)
      {
          return _adlsFileSystemClient.FileSystem.PathExists(accountName, path);
      }
      

      使用ItemExist方法检查路径是否存在的代码。

      string path = "/myfolder/subfolder/testfile.txt";
      if (ItemExist(path))
      {
          string aa = GetItemInfo(path);
          return new string[]
          {
              "Hello",
              aa,
              "World"
          };
      }
      else
      {
          var responseMessage = new HttpResponseMessage(HttpStatusCode.NotFound);
          responseMessage.Content = new StringContent("The file path which you requested is not found");
          throw new HttpResponseException(responseMessage);
      }
      

      对于其他意外异常,我建议您在 ASP.NET Web API 中使用Global Error Handling

      【讨论】:

      • 感谢 bool 函数,它有效。另外,请帮助我了解如何在 azure 上使用 c# 将文件从一个文件夹复制到另一个文件夹
      • 感谢您的链接,但该链接用于移动数据。我只想将相同的数据从一个文件夹复制到另一个文件夹。
      • 很抱歉,目前 C# SDK 中没有实现复制方法。我建议您通过下载文件和上传文件来执行复制操作。
      • 哦,好吧。感谢您对此的帮助。然后我会下载和上传。
      猜你喜欢
      • 2018-10-26
      • 2011-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-03
      • 2018-10-22
      相关资源
      最近更新 更多