深入淺出Blazor webassembly之程序配置



=================================
launchsettings.json profiles 定義文件
=================================
文件位置: roperties\launchSettings.json, 該文件在 dotnet core 項目啟動時會被自動加載, 不同的dotnet項目類型, 會有不同格式的launchsettings.json, 一旦項目類型確定后, 這個json文件的可配置項也就確定下來了, 所以我們不能在該json文件中增加配置項.

對於 BlazorWebAssembly 類型的項目, 這個配置文件包含兩個部分, 一個是 iisSettings 配置(不重要, 暫時忽略), 另一個是 profiles 配置. 默認 BlazorWebAssembly 提供了兩個 profile, 我們也可以增加新的 profile, 比如增加 stg/dev/prod 幾個環境的profile.

但需要說明的是, 因為 launchsettings.json 格式是固定的, 這里僅僅是增加了多個stg/dev/prod profile 名, 我們不能直接在這里增加自定義的配置項.

如何為 dotnet 程序指定 profile?
在 dotnet run 命令行中加上  --launch-profile 參數, 即可指定要加載的 profile.
dotnet run  --launch-profile <launch-profile>  

可以在該 json 文件頭指定其 schema 信息, 這樣 vscode 就能提供自動補全編輯功能.
"$schema":"http://json.schemastore.org/launchsettings.json"


定義一個 blazorDemo1-dev profile:

    "blazorDemo1-dev": {
      "commandName": "Project",
      "dotnetRunMessages": "true",
      "launchBrowser": true,
      "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
      "applicationUrl": "http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "dev"
      }
    }

需要特別說明的是:
commandName 是指定 asp.net core 的啟動模式, 取值應該設置為 Project,  但我估計對於blazor wasm 應該不重要
ASPNETCORE_ENVIRONMENT 設定具體的env名, 這個env在 appsettings.json 文件中會使用到.
 
啟用 blazorDemo1-dev profile的命名:

dotnet run  --launch-profile  blazorDemo1-dev

 

=================================
appsettings.json 應用程序自定義配置文件
=================================
launchSettings.json 不允許增加自定義配置項, 但 wwwroot\appsettings.json 可以增加, 甚至可為不同的 env 定義不同的 appsettings.json 文件, 文件名規范是:  appsettings.{ASPNETCORE_ENVIRONMENT}.json

以 blazorDemo1-dev profile 為例, 因為 ASPNETCORE_ENVIRONMENT 取值為 dev, 所以可增加一個 appsettings.dev.json 配置文件, 這樣就相當於有兩個配置文件, appsettings.json 和  appsettings.dev.json , 如果一個配置項在兩個文件中都定義了, 自然以指定環境的配置文件為准.

需要說明的是 appsettings.json 配置文件, 在瀏覽器端是完全可見的, 所以不能用來存儲敏感信息.
appsettings.json 文件內容:

{
    "appid":"appid123",     //普通key value
    "aaa.a1":"default",     //構造多層 section , 代碼上不認為是多層  
    "bbb":{                 //構造真實的多層 section       
        "b1":"b1value",
        "b2":"b2value"
    },
    "ccc:c1":"c1value",      //另一種構造真實的多層 section 的寫法,完全等價於上面 bbb section  
    "ccc:c2":"c2value"   
}

 

Program.cs 文件讀取配置的代碼:

 public static async Task Main(string[] args)
{
    var builder = WebAssemblyHostBuilder.CreateDefault(args);

    builder.RootComponents.Add<App>("#app");
    builder.Services.AddScoped(sp => new HttpClient { 
        BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

    //讀取 appsettings.json 文件的 aaa.a1 取值
    var a1=builder.Configuration["aaa.a1"]; 
    Console.WriteLine("aaa.a1="+a1);
    
    //多層section取值, 方法1: 使用Bind的方式先獲取第一層 section, 然后使用 Dictionary<k,v> 來獲取第二層 section值
    var dict=new Dictionary<string, string>();
    builder.Configuration.Bind("bbb",dict);   
    Console.WriteLine("bbb:b1="+dict["b1"]); 
    
    //多層section取值, 方法2: 使用冒號表達葉子節點, 即可直接獲取葉子節點的值  
    var b1Another=builder.Configuration["bbb:b1"]; 
    Console.WriteLine("bbb:b1="+b1Another);
    
    await builder.Build().RunAsync();
}

 

=================================
為應用程序增加基於內存的Configuration data
=================================

上面講過 appsettings.json 會被自動下載到瀏覽器端, 所以絕對不能存敏感, 這里給出一個安全性稍微好一點的方法, 將配置項寫死到C#代碼中, 微軟提供了MemoryConfigurationSource 類, 使用這個類設置配置項, 在讀取的時候, 完全和 appsettings.json 一樣, 非常方便.

 

Program.cs 文件設置配置的代碼:

using Microsoft.Extensions.Configuration.Memory;

public static async Task Main(string[] args)
{
    //other code
    var builder = WebAssemblyHostBuilder.CreateDefault(args);

    var dict2=new Dictionary<string, string>();
    dict2.add("xxx.x1":"x1value"); //包含xxx.x1一個層次section 
    dict2.add("yyy:y1":"y1value"); //包含yyy 和 y1兩個層次section 
    dict2.add("yyy:y2":"y2value"); //包含yyy 和 y2兩個層次section 
    var memoryCfg=new MemoryConfigurationSource(){InitialData=dict2};
    builder.Configuration.Add(memoryCfg);
    
    //other code
}

 

=================================
在 razor 文件中使用依賴注入的方式獲取 configuration data
=================================

前面示例都是在 Program.cs 中讀取 appsettings 設置, 其實在 razor 文件中, 讀取也非常方便, 注入一個 IConfiguration 對象.

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration 

public void getCfgValue()
{

    //讀取 appsettings.json 文件    
    var x1=Configuration["xxx.x1"]; 
    Console.WriteLine("xxx.x1="+x1);
    
    var y1=Configuration["yyy:y1"]; 
    Console.WriteLine("yyy:y1="+y1);    
 
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM