Unable to upload file with emulator, problem with controller

Viewed 88

I'm trying to make a blob gallery in VS2019. I created an ASP .NET core (MVC) project with HTTPS configuration, .NET Core 3.1 and no authentication. I have blob storage in Azure, but in this project I'm using Azure Storage Explorer with the emulator enabled. When I start a project it shows me a good html page and the button I can select to upload it works fine but when I press the upload button I get the error "https: // localhost: 44330 / Home / UploadAsync." I think it might be due to a bug that I don't see in homecontroller, because I have implement it and html with css files.

I will add that the connection is made in appsettings.json file using the command "StorageConnectionString": "UseDevelopmentStorage=true". After it in the emulator I see new folder which name covers with code. I'm using WindowsAzure.Storage package.

Home Controller code:

namespace WebApplication.Controllers
{
    public class HomeController : Controller
    {
       
        static CloudBlobClient _blobClient;
        const string _blobContainerName = "imagecontainer";
        private readonly IConfiguration _configuration;
        static CloudBlobContainer _blobContainer;

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

        public async Task<ActionResult> Index()
        {
            try
            {
                var storageConnectionString = _configuration.GetValue<string>("StorageConnectionString");
                var storageAccount = CloudStorageAccount.Parse(storageConnectionString);

                _blobClient = storageAccount.CreateCloudBlobClient();
                _blobContainer = _blobClient.GetContainerReference(_blobContainerName);
                await _blobContainer.CreateIfNotExistsAsync();

                await _blobContainer.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });

                List<Uri> allBlobs = new List<Uri>();
                BlobContinuationToken blobContinuationToken = null;
                do
                {
                    var response = await _blobContainer.ListBlobsSegmentedAsync(blobContinuationToken);
                    foreach (IListBlobItem blob in response.Results)
                    {
                        if (blob.GetType() == typeof(CloudBlockBlob))
                            allBlobs.Add(blob.Uri);
                    }
                    blobContinuationToken = response.ContinuationToken;
                } while (blobContinuationToken != null);

                return View(allBlobs);
            }
            catch (Exception ex)
            {
                ViewData["message"] = ex.Message;
                ViewData["trace"] = ex.StackTrace;
                return View("Error");
            }
        }

        [HttpPost]
        public async Task<ActionResult> UploadAsync()
        {
            try
            {
                var request = await HttpContext.Request.ReadFormAsync();
                if (request.Files == null)
                {
                    return BadRequest("Could not upload files");
                }
                var files = request.Files;
                if (files.Count == 0)
                {
                    return BadRequest("Could not upload empty files");
                }

                for (int i = 0; i < files.Count; i++)
                {
                    var blob = _blobContainer.GetBlockBlobReference(GetRandomBlobName(files[i].FileName));
                    using (var stream = files[i].OpenReadStream())
                    {
                        await blob.UploadFromStreamAsync(stream);

                    }
                }
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                ViewData["message"] = ex.Message;
                ViewData["trace"] = ex.StackTrace;
                return View("Error");
            }
        }

        [HttpPost]
        public async Task<ActionResult> DeleteImage(string name)
        {
            try
            {
                Uri uri = new Uri(name);
                string filename = Path.GetFileName(uri.LocalPath);

                var blob = _blobContainer.GetBlockBlobReference(filename);
                await blob.DeleteIfExistsAsync();

                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                ViewData["message"] = ex.Message;
                ViewData["trace"] = ex.StackTrace;
                return View("Error");
            }
        }

        [HttpPost]
        public async Task<ActionResult> DeleteAll()
        {
            try
            {
                BlobContinuationToken blobContinuationToken = null;
                do
                {
                    var response = await _blobContainer.ListBlobsSegmentedAsync(blobContinuationToken);
                    foreach (IListBlobItem blob in response.Results)
                    {
                        if (blob.GetType() == typeof(CloudBlockBlob))
                            await ((CloudBlockBlob)blob).DeleteIfExistsAsync();
                    }
                    blobContinuationToken = response.ContinuationToken;
                } while (blobContinuationToken != null);

                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                ViewData["message"] = ex.Message;
                ViewData["trace"] = ex.StackTrace;
                return View("Error");
            }
        }

        
        private string GetRandomBlobName(string filename)
        {
            string ext = Path.GetExtension(filename);
            return string.Format("{0:10}_{1}{2}", DateTime.Now.Ticks, Guid.NewGuid(), ext);
        }

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

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
1 Answers

In your html file rename action to Upload instead of UploadAsync

@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
Related