【问题标题】:'ControllerBase.File(byte[], string)' is a method, which is not valid in the given context (CS0119) - in method'ControllerBase.File(byte[], string)' 是一种方法,在给定的上下文 (CS0119) 中无效 - 在方法中
【发布时间】:2020-07-10 15:09:56
【问题描述】:

我正在尝试创建一个应用程序,用户可以在其中上传文本文件,并取回更改后的文本。

我使用 React 作为 FE,使用 ASP.NET Core 作为 BE,使用 Azure 存储作为数据库存储。

这就是我的 HomeController 的样子。 我创建了一个单独的“UploadToBlob”方法来发布数据

    public class HomeController : Controller
    {
        private readonly IConfiguration _configuration;

        public HomeController(IConfiguration Configuration)
        {
            _configuration = Configuration;
        }

        public IActionResult Index()
        {
            return View();
        }

        [HttpPost("UploadFiles")]
        //OPTION B: Uncomment to set a specified upload file limit
        [RequestSizeLimit(40000000)]

        public async Task<IActionResult> Post(List<IFormFile> files)
        {
            var uploadSuccess = false;
            string uploadedUri = null;

            foreach (var formFile in files)
            {
                if (formFile.Length <= 0)
                {
                    continue;
                }

                // read directly from stream for blob upload      
                using (var stream = formFile.OpenReadStream())
                {
                    // Open the file and upload its data
                    (uploadSuccess, uploadedUri) = await UploadToBlob(formFile.FileName, null, stream);

                }

            }

            if (uploadSuccess)
            {
                //return the data to the view, which is react display text component.
                return View("DisplayText");
            }
            else
            {
                //create an error component to show there was some error while uploading
                return View("UploadError");
            }
        }

        private async Task<(bool uploadSuccess, string uploadedUri)> UploadToBlob(string fileName, object p, Stream stream)
        {
            if (stream is null)
            {
                try
                {
                    string connectionString = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING");

                    // Create a BlobServiceClient object which will be used to create a container client
                    BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);

                    //Create a unique name for the container
                    string containerName = "textdata" + Guid.NewGuid().ToString();

                    // Create the container and return a container client object
                    BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);

                    string localPath = "./data/";
                    string textFileName = "textdata" + Guid.NewGuid().ToString() + ".txt";
                    string localFilePath = Path.Combine(localPath, textFileName);

                    // Get a reference to a blob
                    BlobClient blobClient = containerClient.GetBlobClient(textFileName);

                    Console.WriteLine("Uploading to Blob storage as blob:\n\t {0}\n", blobClient.Uri);

                    FileStream uploadFileStream = File.OpenRead(localFilePath);
                    await blobClient.UploadAsync(uploadFileStream, true);
                    uploadFileStream.Close();
                }
                catch (StorageException)
                {
                    return (false, null);
                }
                finally
                {
                    // Clean up resources, e.g. blob container
                    //if (blobClient != null)
                    //{
                    //    await blobClient.DeleteIfExistsAsync();
                    //}
                }
            }
            else
            {
                return (false, null);
            }

        }

    }

但是控制台抛出错误,说“'ControllerBase.File(byte[], string)'是一种方法,在给定的上下文中无效(CS0119)”

由于这个错误,另一个错误跟随“'HomeController.UploadToBlob(string, object, Stream)': 不是所有的代码路径都返回一个值(CS0161)”

我的问题是

  1. 像我一样创建一个单独的方法是不是更好?
  2. 如何解决有关“文件”在 UploadToBlob 方法中有效的问题?
  3. 如果我想添加文件类型验证,应该在哪里进行?德克萨斯州只有文本文件是有效的
  4. 如果我想从上传的文本文件中读取文本字符串,我应该在哪里调用
  string contents = blob.DownloadTextAsync().Result;

  return contents;
  1. 如何将“内容”传递给我的反应组件?像这样?
    useEffect(() => {
        fetch('Home')
            .then(response => response.json())
            .then(data => {
                setForcasts(data)
            })
    }, [])

感谢您帮助这个超级新手使用 ASP.NET Core!

【问题讨论】:

    标签: reactjs azure asp.net-core azure-blob-storage


    【解决方案1】:

    你可能在 MVC 控制器中有这个方法,其中存在 File 方法。添加您的代码System.IO.File 而不是File

    【讨论】:

      【解决方案2】:

      1) 上传可以放在单独的方法中,也可以放在单独的类中处理blob操作

      2) File 是控制器方法之一的名称,如果要从 System.IO 命名空间中引用 File 类,则需要完全限定名称

      FileStream uploadFileStream = System.IO.File.OpenRead(localFilePath);
      

      对于另一个编译错误,您需要从 UploadToBlob 方法返回一些内容,现在它不会从 try 块返回任何内容

      3) 文件类型验证可以放入控制器动作方法中

      4) 这取决于您打算如何处理文本以及您将如何使用它。会不会是控制器的新动作(新的 API 端点)?

      5) 你可以创建一个新的 API 端点来下载文件

      更新:

      对于单词替换,您可以使用类似的方法:

      private Stream FindMostFrequentWordAndReplaceIt(Stream inputStream)
      {
          using (var sr = new StreamReader(inputStream, Encoding.UTF8)) // what is the encoding of the text? 
          {
              var allText = sr.ReadToEnd(); // read all text into memory
              // TODO: Find most frequent word in allText
              // replace the word allText.Replace(oldValue, newValue, stringComparison)
              var resultText = allText.Replace(...);
      
              var result = new MemoryStream();
              using (var sw = new StreamWriter(result))
              {
                  sw.Write(resultText);
              }
              result.Position = 0;
              return result;
          }
      }
      

      它将以这种方式在您的 Post 方法中使用:

      using (var stream = formFile.OpenReadStream())
      {
          var streamWithReplacement = FindMostFrequentWordAndReplaceIt(stream);
      
          // Upload the replaced text:
          (uploadSuccess, uploadedUri) = await UploadToBlob(formFile.FileName, null, streamWithReplacement);
      
      }
      

      【讨论】:

      • 谢谢!关于答案,Q3,我可以在尝试中添加验证吗? Q4,我想从上传的文件中获取文本,并找到最常用的单词并更改该单词。也许最好创建另一个 API 控制器,我可以在其中传递文件中的文本并调用该控制器以使用 ```` ``` string contents = blob.DownloadTextAsync().Result; 传递数据;返回内容; ```这样吗?
      • 您也可以直接在Post 方法中验证文件名。 IFromFile 拥有FileName 的属性。
      • Q4 - 如果更改最常用词的操作是在将blob上传到blob存储之前完成的,那么它可以在Post方法中调用(并在文件流上执行)数据来自IFromFile)。如果操作是在上传之后独立完成的,那么它可能是控制器中的一个新操作,然后需要首先从存储中下载文件,然后进行更改,然后再上传回 blob 存储。
      • 我希望用户更新的文本文件是 - 找到最常用的单词并在文本中更改该单词并将更改后的文本显示给用户。如果可能的话,我想 1. 在调用 Post 方法时在上传之前获取文件的文本内容并保存该内容,所以我在 POST 方法中添加了“DownloadTextAsync()”方法,但似乎我是将此方法调用到错误的主题?我知道'blobClient'是对blob的引用,我可以在哪里获取文件的数据,但这一定是错误的?
      • 另外,我似乎不能使用“CloudBlobContainer”或“CloudBlockBlob blob”。是不是因为在POST方法里面,blob刚刚初始化,执行这两个的时候不存在?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-21
      • 2012-06-06
      相关资源
      最近更新 更多