dotnet9網站回歸blazor重構,訪問速度飛快,交互也更便利了!

dotnet9網站回歸blazor重構,訪問速度飛快,交互也更便利了!

本來站長奔著體驗.net 8 blazor web app的,在razor pages中添加了razor 組件,但目前該混合模式razor組件無法交互,頁面還出現了重連置灰ui,索性直接用blazor server重構,經過幾天的奮戰,網站前台已經用blazor server完全替換razor pages,煩人的重連也解決了,現在訪問網站飛快,不知道是不是錯覺,個人感覺很好。

最后更新 2023/6/23 上午9:10
沙漠尽头的狼
预计阅读 9 分钟
分类
Blazor
标签
.NET C# Blazor Razor Pages Dotnet9

大家好,我是沙漠盡頭的狼。

dotnet9網站回歸blazor重構,訪問速度確實飛快,同時用上blazor的交互能力,站長也同步添加了幾個在線工具,這篇文章分享下blazor的重構過程,希望對大家網站開發時做技術選型有個參考。

1. 先聊聊razor pages

上個版本網站前台使用的razor pages開發,當時選擇這個技術棧主要是為了搜尋引擎的seo優化考慮。

關於mvc和razor pages哪個更優, 我們這裡只說說razor pages相對的優勢。

首先,razor pages相對於mvc來說,更加簡單和直觀。由於razor pages將視圖和處理邏輯封裝在同一個頁面中,開發人員可以更容易地理解和維護代碼。對於小型項目或者只有少量頁面的應用來說,razor pages可以提供更快的開發速度和更簡潔的代碼結構,這是站長當時從mvc重構成razor pages的主要選擇理由。

其次,razor pages在seo(搜尋引擎優化)方面具有一定的優勢。由於razor pages將視圖和處理邏輯封裝在同一個頁面中,搜尋引擎可以更容易地理解和索引頁面的內容。這對於需要更好的搜尋引擎排名的應用來說,是一個重要的考慮因素。

說razor pages優勢,那為啥現在又換blazor了?因為blazor可能又是更好的選擇了,我們接著說。

2. 關鍵聊聊blazor

blazor是一個新興的web開發框架,它可以讓開發人員使用c#語言來編寫web應用程式,而不必使用javascript,當然只能說儘量少用,完全不用也不太現實。相比於razor pages和mvc,blazor提供了一種全新的開發模式,具有許多獨特的優勢和適用場景。

首先,blazor提供了真正的前端開發體驗。傳統的web開發中,前端開發人員需要使用javascript來處理頁面的交互和動態效果,而後端開發人員則負責處理業務邏輯和數據操作。這種分離的開發模式可能導致開發人員之間的溝通和協作問題。而blazor使用c#語言來編寫前端代碼,使得前端和後端開發人員可以使用相同的語言和工具,更加高效地協作開發。

其次,blazor提供了更好的性能和用戶體驗,blazor提供了客戶端和服務端兩種模式(blazor混合模式有機會我們再談):

  • 客戶端模式:blazor使用webassembly技術,在瀏覽器中直接運行編譯後的二進位代碼,可以實現接近原生應用的性能。
  • 服務端模式:與傳統的基於http請求的頁面刷新相比,blazor使用signalr連接來實現實時數據更新和雙向綁定,可以提供更快速和流暢的用戶體驗。

另外,blazor還具有更好的可重用性和組件化開發。blazor提供了豐富的組件庫和工具,可以幫助開發人員更快地構建出漂亮且功能強大的界面。開發人員可以將常用的ui組件封裝成可重用的組件,提高開發效率和代碼質量。

此外,blazor還支持現代化的前端開發技術和工具。開發人員可以使用blazor與現有的javascript庫和框架進行集成,如react、vue.js等。

總之,blazor對於razor pages和mvc來說是一個更好的選擇,特別是對於需要更好的前端開發體驗、更好的性能和用戶體驗以及更好的可重用性和組件化開發的項目來說。然而,選擇使用哪種開發模式還是要根據項目的具體需求和開發團隊的偏好來決定。無論選擇哪種模式,重要的是根據項目的實際情況做出合理的選擇,並且在開發過程中遵循良好的設計原則和最佳實踐。

3. 再聊聊為啥又用blazor了?

站長在去年對網站前台使用blazor server開發過一個版本,當時因為斷線重連體驗的問題,站長選擇用razor pages重構了。

這次站長回歸blazor的轉折點在6月13號 - .net 8 preview 5發布,vs2022預覽版也跟著出了blazor web app項目模板,各個技術群也討論瘋了,站長在razor pages中添加了razor 組件嘗試,微軟確實牛逼,旨在使 blazor 組件能夠滿足客戶端和伺服器端的所有 web ui 需求。。

但目前该模式Razor组件无法交互,页面还出现了重连置灰UI,索性直接用Blazor Server重构,经过几天的奋战,网站前台已经用Blazor Server完全替换Razor Pages,烦人的重连也解决了,现在访问网站飞快,不知道是不是错觉,个人感觉很好。(重连问题参考微软文档【ASP.NET Core BlazorSignalR 指南】和Token佬写的文章 【如何取消Blazor Server烦人的重新连接?】。)

razor pages(mvc)與blazor都使用的razor語法,所以理論上切換是無縫的,核心代碼改動不大,項目代碼文件結構對比看下面截圖,不再贅述,有興趣看源碼吧,兩個版本代碼都在。

razor pages版工程結構 blazor server版工程結構

4. blazor的交互便利:帶來幾個在線工具

對於頁面的事件處理,使用blazor就方便了,下面是昨晚加的4個小工具:

有興趣的朋友可以點擊體驗:https://dotnet9.com/tools, 我們直接貼上4個小工具代碼,你可能會喜歡上blazor的代碼風格。

4.1. json格式化

訪問地址:https://dotnet9.com/tools/jsonformatter

頁面代碼:

@page "/tools/jsonformatter"
@using System.Text.Json

<PageTitle>@_title</PageTitle>

<MApp>
   <h2 style="margin-bottom: 30px; margin-top: 10px; text-align: center;">@_title</h2>

   <div>
       <MTextarea BackgroundColor="grey lighten-2" Solo
                  Color="orange orange-darken-4" TValue="string" @bind-Value="_inputJson"
                  Label="输入Json" Rows="8" style="font-size:12px;" RowHeight="15" AutoGrow/>
   </div>

   <div>
       <MButton Color="success" class="ma-2" OnClick="() => FormatJson(true)">格式化</MButton>
       <MButton Color="lime" OnClick="() => FormatJson(false)">压缩</MButton>
   </div>

   <div>
       <MTextarea BackgroundColor="amber lighten-4" Solo
                  Color="orange orange-darken-4" TValue="string" @bind-Value="_formattedJson"
                  Label="格式化或压缩后Json" Rows="8" style="font-size:12px;" RowHeight="15" AutoGrow/>
   </div>
</MApp>

@code
{
       private const string? _title = "工具箱-JSON格式化";
   private string? _inputJson;
   private string? _formattedJson;

   private void FormatJson(bool writeIndented)
   {
       try
       {
           var jsonObject = JsonDocument.Parse(_inputJson).RootElement;
           _formattedJson = JsonSerializer.Serialize(jsonObject, new JsonSerializerOptions { WriteIndented = writeIndented });
       }
       catch (JsonException)
       {
           _formattedJson = "无效的JSON格式";
       }
   }
}

4.2.在線字符串編碼工具

訪問地址:https://dotnet9.com/tools/string-encoder

頁面代碼:

@page "/tools/string-encoder"

<PageTitle>@Title</PageTitle>

<MApp>
   <h2 style="margin-bottom: 30px; margin-top: 10px; text-align: center;">@Title</h2>

   <p>
       <MTextarea BackgroundColor="grey lighten-2"
                  Color="cyan" Solo TValue="string" @bind-Value="_inputString"
                  Label="输入字符串"/>
   </p>

   <p>
       <MTextarea BackgroundColor="amber lighten-4" Solo
                  Color="orange orange-darken-4" TValue="string" @bind-Value="_encodedOrDecodeString"
                  Label="编/解码结果"/>
   </p>

   <p>
       <MButton OnClick="@Encode">编码</MButton>
       <MButton OnClick="@Decode">解码</MButton>
       <MButton OnClick="@Clear">清空</MButton>
   </p>
</MApp>

@code {
   private const string Title = "工具箱-在线字符串编码工具";
   private string? _inputString;
   private string? _encodedOrDecodeString;

   private void Encode()
   {
       _encodedOrDecodeString = System.Web.HttpUtility.UrlEncode(_inputString);
   }

   private void Decode()
   {
       _encodedOrDecodeString = System.Web.HttpUtility.UrlDecode(_inputString);
   }

   private void Clear()
   {
       _inputString = string.Empty;
       _encodedOrDecodeString = string.Empty;
   }

}

4.3.倒計時

訪問地址:https://dotnet9.com/tools/countdown

頁面代碼:

@page "/tools/countdown"

<PageTitle>@Title</PageTitle>

<MApp>
   <h2 style="margin-bottom: 30px; margin-top: 10px; text-align: center;">@Title</h2>

   <p>
       <MTextField Label="持续时间(秒)" Type="number" TValue="int" @bind-Value="@_duration"/>
   </p>

   <p>
       <MButton Color="success" class="ma-2" OnClick="@StartCountdown" Disabled="@_isCountingDown">开始</MButton>
       <MButton Color="pink" class="ma-2 white--text" OnClick="@PauseCountdown" Disabled="!_isCountingDown">暂停</MButton>
       <MButton Color="deep-orange" class="ma-2 white--text" OnClick="@ResetCountdown" Disabled="!_isCountingDown">重置</MButton>
       剩余时间(秒):@_remainingTime
   </p>
   <div class="text-center">
       <MProgressCircular Value="@_remainingTimePercent" Size="100" Width="15" Rotate="360" Color="teal">@_remainingTime</MProgressCircular>
   </div>
</MApp>

@code {
   private const string Title = "工具箱-倒计时";
   private int _duration = 20;
   private int _remainingTime;
   private int _remainingTimePercent;
   private bool _isCountingDown;
   private bool _isPause;
   private CancellationTokenSource? _countdownTokenSource;

   private async Task StartCountdown()
   {
       if (_duration < 0)
       {
           _duration = 10;
       }
       if (_isCountingDown)
       {
           return;
       }
       _isCountingDown = true;
       if (!_isPause || _remainingTime <= 0)
       {
           _remainingTime = _duration;
           ChangeRemainingTimePercent();
       }
       _countdownTokenSource = new CancellationTokenSource();

       await Countdown(_countdownTokenSource.Token);
   }

   private void PauseCountdown()
   {
       if (!_isCountingDown)
       {
           return;
       }
       _isCountingDown = false;
       _isPause = true;
       _countdownTokenSource?.Cancel();
   }

   private async void ResetCountdown()
   {
       _isPause = false;
       if (_isCountingDown && _countdownTokenSource != null)
       {
           await _countdownTokenSource.CancelAsync();
       }

       _remainingTime = _duration;
       _isCountingDown = false;
       ChangeRemainingTimePercent();
   }

   private async Task Countdown(CancellationToken cancellationToken)
   {
       while (_remainingTime > 0)
       {
           await Task.Delay(1000, cancellationToken);
           _remainingTime--;
           ChangeRemainingTimePercent();

           if (cancellationToken.IsCancellationRequested)
           {
               return;
           }
       }

       _isCountingDown = false;
   }

   private async void ChangeRemainingTimePercent()
   {
       _remainingTimePercent = (int)(_remainingTime * 100.0 / _duration);
       await InvokeAsync(StateHasChanged);
   }

}

4.4.時間戳轉換

訪問地址:https://dotnet9.com/tools/timestamp

站长原来写过一篇,可以看这里:使用Blazor做个简单的时间戳在线转换工具

5. 總結

網站可能存在bug,不,一定存在bug,站長會一直重構疊代下去。

很高興將網站前台重構後分享這個喜悅給大家,祝大家端午安康。

Keep Exploring

延伸阅读

更多文章
同分类 / 同标签 2024/2/29

winform中也可以這樣做數據展示

在做winform開發的過程中,經常需要做數據展示的功能,之前一直使用的是gridcontrol控制項,今天想通過一個示例,跟大家居間一下如何在winform blazor hybrid中使用ant design blazor中的table組件做數據展示。

继续阅读
同分类 / 同标签 2024/2/29

winform的界面也可以變好看?

前幾天跟大家居間了在winform中使用blazor hybrid,而且還說配上blazor的ui可以讓我們的winform程式設計的更加好看,接下來我想以一個在winform blazor hybrid中繪圖的例子來進行說明,希望對你有所幫助。

继续阅读