【问题标题】:Configuring Azure Blob access in ASP.Net 5在 ASP.Net 5 中配置 Azure Blob 访问
【发布时间】:2017-01-02 12:39:18
【问题描述】:

我正在 Visual Studio 2015 中创建一个 ASP.Net 5 WebAPI 应用程序,我需要使用 Azure Blob。

要使用 Azure blob,来自官方文档:https://azure.microsoft.com/en-us/documentation/articles/storage-dotnet-how-to-use-blobs/,您需要在 <appSettings /> 中的 app.configweb.config 文件中放置一个键值对,如下所示:

<appSettings>
    <add key="StorageConnectionString" value="DefaultEndpointsProtocol=https;AccountName=account-name;AccountKey=account-key" />
</appSettings>

但问题是,如果您使用的是 ASP.Net 5,则没有名为 app.configweb.config 的此类文件。

如果我使用的是 ASP.Net 5,我应该把 StorageConnectionString 放在哪里?

【问题讨论】:

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


【解决方案1】:

ASP.NET Core 提供了多种不同的配置选项。应用程序配置数据可能来自文件(例如 JSON、XML 等)、环境变量、内存中的集合等。

它适用于选项模型,因此您可以将强类型设置注入您的应用程序。您还可以创建自定义配置提供程序,这可以为您带来更大的灵活性和可扩展性。

根据您的要求,您可以按照以下步骤来达到您的目的:

在您的 appsetting.json 中创建一个名为 AzureStorageConfig 的部分:

"AzureStorageConfig": {
  "AccountName": "<yourStorageAccountName>",
  "AccountKey": "<yourStorageAccountKey>"
}

像这样创建一个名为 AzureStorageConfig 的类:

public class AzureStorageConfig
{
    public string AccountName { get; set; }
    public string AccountKey { get; set; }
}

然后像这样在 Startup.cs 中配置服务:

public void ConfigureServices(IServiceCollection services)
{   
    // Add framework services.
    services.AddMvc();
    // Setup options with DI
    services.AddOptions();
    services.Configure<AzureStorageConfig>(Configuration.GetSection("AzureStorageConfig"));
}

然后通过这样的控制器访问它:

private AzureStorageConfig _storageConfig;
public HomeController(IOptions<AzureStorageConfig> config)
{
    _storageConfig = config.Value;
}

更多详情可以参考这个Tutorial

【讨论】:

  • 您的解决方案可以工作。但我还是不喜欢。如果您是 NodeJS,您可以简单地将所有内容放入一个文件并将该文件解析为 JSON 对象。然后你就可以轻松得到你想要的。在我看来,这个框架试图隐藏步骤,这将使人们很难追溯问题所在。
【解决方案2】:

解决方案很简单。你不必经历他们官方教程中提到的乏味/荒谬的步骤。

var storageAccount = new CloudStorageAccount(
    new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(
        "{account_name}", 
        "key"), true);

我不知道微软为什么要竭尽全力让人们的生活复杂化。

【讨论】:

  • 因为现在您的文件中有“神奇值”,如果这些值发生变化,您需要重新编译和重新部署您的网站。此外,ASP.NET 5 有一个appSettings.json 文件。
  • 其实官方文档在“解析连接字符串”一节中提到了在没有配置文件的情况下传入连接字符串的方式。
  • @Zhaoxing Lu 我用过它,它只是失败了。我应该把“StorageConnectionString”放在哪里。你有没有在你说之前尝试过你的求婚方法?
  • 当然。这是将存储连接字符串传递给客户端库的最简单方法。你能在这里分享你的代码让我看看吗?
  • CloudStorageAccount 用于过时的 NuGet 包...
猜你喜欢
  • 1970-01-01
  • 2021-07-30
  • 1970-01-01
  • 2021-01-14
  • 2021-09-17
  • 1970-01-01
  • 2014-08-22
  • 2017-04-25
  • 2021-04-26
相关资源
最近更新 更多