'ControllerBase.File(byte[], string)' 是一种方法,在给定的上下文中无效 (CS0119) - 在方法中

IT技术 reactjs azure asp.net-core azure-blob-storage
2021-05-25 10:57:21

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

我使用 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)': not all code paths return a value (CS0161)”

我的问题是

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

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

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

2个回答

1)把上传放到单独的方法里就可以了,也可以放到单独的类来处理blob操作

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

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);

}

您可能在存在 File 方法的 MVC 控制器中拥有此方法。添加您的代码System.IO.File而不是File