---
# System prepended metadata

title: Blazor Webassembly 透過 URL設定多國語系
tags: [i18n, Blazor Webassembly]

---

## 參考文件
* [多國語系魔術](https://ithelp.ithome.com.tw/articles/10252226)
* [ASP.NET Core Blazor 全球化和本地化](https://learn.microsoft.com/zh-tw/aspnet/core/blazor/globalization-localization?view=aspnetcore-6.0&pivots=webassembly)
* [Localization in Blazor WebAssembly Applications](https://code-maze.com/localization-in-blazor-webassembly-applications/)

## 呈現結果
![](https://hackmd.io/_uploads/H1Slrldbo.gif)

## 環境
* Blazor Webassembly
* .Net 6

## 專案
[Github](https://github.com/Airethz/BlazorWASM_i18nByUrl)

## 操作流程
### 1. 安裝套件
* 套件名稱：Microsoft.Extensions.Localization
![](https://hackmd.io/_uploads/ByGg6A8-i.png)

### 2. 服務註冊
在 ==Program.cs== 加入：
```csharp!
builder.Services.AddLocalization();
```
![](https://hackmd.io/_uploads/HkItkywbj.png)

### 3. 取得JS儲存的語系
在 ==Program.cs== 加入：
```csharp=
var host = builder.Build();
CultureInfo culture;
var js = host.Services.GetRequiredService<IJSRuntime>();
var result = await js.InvokeAsync<string>("blazorCulture.get");//取得 JS localStorage的儲存內容
if (result != null)
{
    culture = new CultureInfo(result);
}
else
{
    culture = new CultureInfo("en-US");
    await js.InvokeVoidAsync("blazorCulture.set", "en-US");
}
CultureInfo.DefaultThreadCurrentCulture = culture;
CultureInfo.DefaultThreadCurrentUICulture = culture;
```
![](https://hackmd.io/_uploads/HyonEgPZo.png =x400)


### 4. 專案設定
點擊專案後，加入：
```csharp!
<BlazorWebAssemblyLoadAllGlobalizationData>true</BlazorWebAssemblyLoadAllGlobalizationData>
```
![](https://hackmd.io/_uploads/SyWO-kv-o.png)

#### 未設定導致的錯誤訊息
![](https://hackmd.io/_uploads/B1kdyewWs.png =x350)

### 5. JS的blazorCulture存取設定
建立Javascript用來讀取url參數內容並把內容存至localStorage，以及取得組合url用的lang字串。
檔案位置：wwwroot/js/settingCulture.js

```javascript=
/* loading時檢查lang參數內容 */
window.onload = function () {
    var langValue = getParameterByName("lang");
    if (langValue.length > 0 && window.localStorage['BlazorCulture'] != langValue) {
        window.localStorage['BlazorCulture'] = langValue;
    }
}

function getParameterByName(name, url = window.location.href) {
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

window.blazorCulture = {
    get: () => window.localStorage['BlazorCulture'],
    set: (value) => window.localStorage['BlazorCulture'] = value
};

/*取得組合url用的lang字串*/
function GetLangString() {
    var langVaule = window.localStorage['BlazorCulture'];
    var result = "";
    if (langVaule.length > 0) {
        result = "lang=" + langVaule;
    }
    return result;
}
```

### 6. script嵌入index
把上一步建立的js嵌入wwwroot/index.html
```htmlmixed!
<script src="js/settingCulture.js"></script>
```

### 7. 建立資源檔
* 新增ResourceFiles資料夾存放檔案
* 加入 :arrow_right: 新增項目 :arrow_right: 資源檔
![](https://hackmd.io/_uploads/r1km4JwZo.png)

:::success
命名規則：
* 檔名.resx
    ex. ==Resource.resx==
* 檔名.語系.resx
    ex. ==Resource.en.resx==、==Resource.zh-TW.resx==
:::

### 8. 設定資源檔
設定語系所呈現的文字。
:::danger
注意事項：Resource.resx的存取修飾詞要設定為Public，其他Resource檔案(ex. Resource.en.resx)不用設定。
:::
![](https://hackmd.io/_uploads/r1MAVJDWs.png)

### 9. 頁面顯示內容設定
使用 ==IStringLocalizer== 呼叫名稱對應的值
```htmlembedded=
@using Blazor_WASM_Localization.Shared.ResourceFiles
@inject Microsoft.Extensions.Localization.IStringLocalizer<Resource> localizer
    
@localizer["helloWorld"] <!--顯示對應的語系內容-->
```

### 10. Url放入語系參數
從js呼叫GetLangString方法獲得url參數
檔案位置：Shared/NavMenu.razor
![](https://hackmd.io/_uploads/r1VWVg_bo.png)

![](https://hackmd.io/_uploads/HJOWNe_Ws.png)


