ASP.NET Core从azure&删除图像blob来自数据库

时间:2018-06-11 21:06:01

标签: c# asp.net azure-storage-blobs

我有一个ASP.NET应用程序,可以成功将图像上传到azure容器。我正在尝试创建一个删除blob中特定图像的函数,并从数据库中删除该图像。从数据库中删除它并不困难,但尝试从azure中删除它会引发异常。我已经在网上搜索了答案,但没有!一切都有帮助!以下是代码:

  

错误异常

An unhandled exception occurred while processing the request.
ArgumentNullException: Value cannot be null.
Parameter name: connectionString
Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(string connectionString)
  

InterfaceService.cs

 public CloudBlobContainer GetBlobContainer(string azureCString, string containerName)
    {
        var account = CloudStorageAccount.Parse(AzureCString);
        var blobClient = account.CreateCloudBlobClient();
        return blobClient.GetContainerReference(containerName);
    }
  

Products.cs

 public async Task<IActionResult> Delete(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var product = await _context.Product
            .SingleOrDefaultAsync(m => m.Id == id);
        if (product == null)
        {
            return NotFound();
        }

        return View(product);
    }


    [HttpPost, ActionName("Delete")]
    public async Task<IActionResult> DeleteConfirmed(int id, IFormFile file)
    {
        var product = await _context.Product.SingleOrDefaultAsync(m => m.Id == id);
        var container = _interfaceService.GetBlobContainer(AzureCString, "azureCstring");
        var content = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
        var fileName = content.FileName.Trim('"');
        var blob = container.GetBlockBlobReference(fileName);
        await blob.DeleteIfExistsAsync();

        _context.Product.Remove(product);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }

1 个答案:

答案 0 :(得分:0)

根据例外情况,您似乎连接字符串为null。您可以在GetBlobContainer函数中使用带有硬代码的连接字符串并再次测试它。

根据我的理解,您需要在GetBlobContainer函数中将代码var account = CloudStorageAccount.Parse(AzureCString);更改为var account = CloudStorageAccount.Parse(azureCString);

public CloudBlobContainer GetBlobContainer(string azureCString, string containerName)
    {
        var account = CloudStorageAccount.Parse(azureCString); // change AzureCString to azureCString
        var blobClient = account.CreateCloudBlobClient();
        return blobClient.GetContainerReference(containerName);
    }

还要确保 DeleteConfirmed 功能中的AzureCString不为空。正如我所提到的,你可以使用硬代码连接字符串。它应该工作。