'ControllerBase.File(byte [],string)'是一个方法,在给定的上下文中无效(CS0119)-in方法 [英] 'ControllerBase.File(byte[], string)' is a method, which is not valid in the given context (CS0119) - in method

查看:228
本文介绍了'ControllerBase.File(byte [],string)'是一个方法,在给定的上下文中无效(CS0119)-in方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to create an app where user can upload a text file, and gets the altered text back.

我将React用作FE,将BE.NET Core和BE.Azure用作数据库存储.

I am using React as FE and ASP.NET Core for BE and Azure storage for the database storage.

这是我的HomeController的外观. 我创建了一个单独的"UploadToBlob"方法来发布数据

This is how my HomeController looks like. I created a separate "UploadToBlob" method, to post the data

    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 [],字符串)'是一种方法,在给定的上下文中无效(CS0119)"

but the console throws errors, saying "'ControllerBase.File(byte[], string)' is a method, which is not valid in the given context (CS0119)"

由于此错误,"HomeController.UploadToBlob(string,object,Stream)'之后出现另一个错误:并非所有代码路径都返回值(CS0161)"

And because of this error, another error follows "'HomeController.UploadToBlob(string, object, Stream)': not all code paths return a value (CS0161)"

我的问题是

  1. 像我一样创建一个单独的方法是更好的主意吗?
  2. 如何解决有关文件"在UploadToBlob方法内部有效的问题?
  3. 如果要添加文件类型验证,应该在哪里进行?特例仅文本文件存在
  4. 如果我想从上传的文本文件中读取文本字符串,应该在哪里调用

  string contents = blob.DownloadTextAsync().Result;

  return contents;

  1. 如何将内容"传递给我的React组件?这样的东西?

    useEffect(() => {
        fetch('Home')
            .then(response => response.json())
            .then(data => {
                setForcasts(data)
            })
    }, [])

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

Thanks for helping this super newbie with ASP.NET Core!

推荐答案

1)可以将上载置于单独的方法中,也可以将其放入单独的类中以处理blob操作

1) It is ok to put uploading into separate method, it could also be put into a separate class for handling blob operations

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

2) File is the name of one of the controllers methods, if you want to reference the File class from System.IO namespace, you need to fully qualify the name

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

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

To the other compile error, you need to return something from the UploadToBlob method, now it does not return anything from the try block

3)可以在控制器操作方法中添加文件类型验证

3) File type validation can be put into the controller action method

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

4) it depends on what you plan to do with the text and how are you going to use it. Would it be a new action of the controller (a new API endpoint)?

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

5) you could create a new API endpoint for downloading files

更新:

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

For word replacement you could use a similar method:

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方法中使用:

it would be used in your Post method this way:

using (var stream = formFile.OpenReadStream())
{
    var streamWithReplacement = FindMostFrequentWordAndReplaceIt(stream);

    // Upload the replaced text:
    (uploadSuccess, uploadedUri) = await UploadToBlob(formFile.FileName, null, streamWithReplacement);

}

这篇关于'ControllerBase.File(byte [],string)'是一个方法,在给定的上下文中无效(CS0119)-in方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆