萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET 核心程式設計 25 類常用函式精選:DateTime、字串、編碼、XML、Session、Request 等實用技巧

分類速查索引

  1. DateTime 日期時間處理
  2. 型別轉換 (字串 ⇄ 數值)
  3. 字串格式化與操作
  4. 編碼與位元組轉換
  5. StringBuilder 高效字串建構
  6. 子字串擷取
  7. 取得客戶端 IP (含代理)
  8. Session 狀態管理
  9. QueryString 參數傳遞
  10. XML 節點建立與操作
  11. Response 輸出與導向
  12. 字元判斷 (空白、標點)
  13. 字元與 Unicode 代碼互轉
  14. Trim 與 Replace 字串清理

詳細範例與說明

1. DateTime 日期時間

DateTime now = DateTime.Now;

int year   = now.Year;        // 年
int month  = now.Month;       // 月
int day    = now.Day;         // 日
int hour   = now.Hour;        // 時 (24小時制)
int minute = now.Minute;      // 分
int second = now.Second;      // 秒
int ms     = now.Millisecond; // 毫秒

// 常用格式化
string fmt1 = now.ToString("yyyy-MM-dd");           // 2024-01-15
string fmt2 = now.ToString("yyyy/MM/dd HH:mm:ss");  // 2024/01/15 14:30:05
string fmt3 = now.ToString("yyyy年MM月dd日");       // 2024年01月15日

2. 型別轉換

// 字串 → int (建議用 TryParse 避免例外)
int.TryParse("123", out int num);   // num = 123
int num2 = int.Parse("123");        // 失敗拋 FormatException

// 數值 → 字串
string s = 12345.ToString();        // "12345"
string s2 = 12345.ToString("N");    // "12,345.00" (千分位)
string s3 = 12345.ToString("C");    // "¥12,345.00" (貨幣,依 CurrentCulture)
string s4 = 12345.ToString("E");    // "1.234500E+004" (科學記號)
string s5 = 12345.ToString("F4");   // "12345.0000" (固定小數位)
string s6 = 12345.ToString("X");    // "3039" (十六進位)
string s7 = 12345.ToString("P");    // "1,234,500.00%" (百分比)

3. 字串長度與編碼位元組

string str = "中國";
int charLen = str.Length;                    // 2 (Char 數)
byte[] bytes = Encoding.Default.GetBytes(str); // 系統預設編碼 (繁中環境通常 Big5)
int byteLen = bytes.Length;                  // 4 (位元組數)

byte[] utf8Bytes = Encoding.UTF8.GetBytes(str); // UTF-8 編碼位元組 (每中文字 3 bytes)
int utf8Len = utf8Bytes.Length;              // 6

4. StringBuilder 高效串接

var sb = new StringBuilder();
sb.Append("中華");
sb.Append("人民");
sb.Append("共和國");
string result = sb.ToString(); // "中華人民共和國"

// 格式化附加
sb.AppendFormat("年份:{0}, 月份:{1}", DateTime.Now.Year, DateTime.Now.Month);

5. Substring 擷取子字串

string src = "ABCDEFG";
// 從索引 2 開始取 3 個字元 (0-based)
string sub = src.Substring(2, 3); // "CDE"

// 從索引 2 取到結尾
string tail = src.Substring(2);   // "CDEFG"

// 安全擷取 (避免 ArgumentOutOfRange)
string safe = src.Length > 5 ? src.Substring(0, 5) : src;

6. 取得客戶端 IP

// 直接連線
string ip = Request.ServerVariables["REMOTE_ADDR"];

// 經過代理/負載平衡器 (Nginx, Azure LB, AWS ALB 等)
string ip = Request.ServerVariables["HTTP_X_FORWARDED_FOR"]?.Split(',')[0].Trim() 
         ?? Request.ServerVariables["HTTP_X_REAL_IP"] 
         ?? Request.ServerVariables["REMOTE_ADDR"];

7. Session 存取

// 寫入
Session["UserName"] = "Admin";

// 讀取 (安全轉型)
string name = Session["UserName"] as string ?? "Guest";

// 移除單一鍵
Session.Remove("UserName");

// 清除所有
Session.RemoveAll(); // 或 Session.Clear()

8. QueryString 取得

// URL: Edit.aspx?fdid=100
string id = Request.QueryString["fdid"]; // "100"

// 安全轉型
int.TryParse(Request.QueryString["fdid"], out int fid);

9. XML 節點操作 (XmlDocument)

XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/Data.xml"));

XmlElement newNode = doc.CreateElement("Item");
newNode.SetAttribute("id", "101");
newNode.InnerText = "新項目內容";

XmlNode root = doc.SelectSingleNode("/Root");
root.AppendChild(newNode);

doc.Save(Server.MapPath("~/Data.xml"));

10. Response 常用操作

Response.Write("直接輸出文字或 HTML");
Response.Write(DateTime.Now);

Response.Redirect("Target.aspx");       // 302 導向
Response.Redirect("Target.aspx", false); // 不結束當前執行緒 (搭配 Context.ApplicationInstance.CompleteRequest())

// 輸出檔案下載
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;filename=report.xlsx");
Response.TransmitFile(Server.MapPath("~/Files/report.xlsx"));
Response.End();

11. 字元判斷

string test = "中 文";
bool isSpace = char.IsWhiteSpace(test, 1); // true (索引 1 為空白)

bool isPunct = char.IsPunctuation(',');   // true (中文逗號)
bool isPunct2 = char.IsPunctuation('A');   // false

12. 字元 ↔ Unicode 代碼點

// 字元 → 數值 (代碼點)
int code = '中';        // 20013 (0x4E2D)
int code2 = "中"[0];    // 同上

// 數值 → 字元
char ch = (char)22269;  // '國' (0x56FD)
string s = char.ConvertFromUtf32(0x1F600); // "😀" (Emoji 需 UTF-32)

13. Trim 與 Replace

string messy = "  Hello World  ";
string clean = messy.Trim();           // "Hello World"
string cleanStart = messy.TrimStart(); // "Hello World  "
string cleanEnd = messy.TrimEnd();     // "  Hello World"

string replaced = "中國".Replace("國", "央"); // "中央"

// 移除所有空白
string noSpace = "A B C".Replace(" ", ""); // "ABC"

// 正則取代 (更強大)
string regexReplaced = Regex.Replace("abc123def", @"\d+", "#"); // "abc#def"

總結

這 25 類函式涵蓋了 ASP.NET Web Forms 時代最核心的伺服器端程式設計需求。雖然現代開發多轉向 ASP.NET Core、前後端分離,但 `DateTime` 格式化、編碼轉換、字串操作、IP 取得、Session/QueryString/Response 操作等基礎 API 在任何 .NET 伺服器端開發中依然是每日必用。建議將常用片段整理為個人/團隊 Snippet 庫 (Visual Studio Code Snippets、ReSharper Live Templates、GitHub Gist),提升編碼效率與一致性。

copyright © 萬盛學電腦網 all rights reserved