iT邦幫忙

2021 iThome 鐵人賽

DAY 7
1
Modern Web

ASP.NET Web Forms 入門 - 30天建立遊艇網頁專案後端及後台功能 C#系列 第 7

Day 7 - Using Global.asax File for Short URL Routing with ASP.NET Web Forms C# 使用全域應用程式類別產生短網址路由功能

  • 分享至 

  • twitterImage
  •  

=x= 🌵 網址顯示方式管理。


短網址功能介紹 :

📌 如果仔細觀察網址,可以發現平常瀏覽的網頁並不會出現副檔名,但是用 Visual Studio 跑出來的網頁都會有副檔名,而且網址就是資料夾的名稱跟檔名的組合,今天要介紹的就是使用全域應用程式類別 Global.asax 來進行網址的管理,如何設定不顯示副檔名,以及用來自訂短網址的製作方式。

👀 短網址案例 : Accupass 設定活動頁面短網址

👀 Global.asax 介紹 : Global.asax 文件是什麼

👀 應用程序生命週期概述 : ASP.NET Application Life Cycle Overview for IIS 5.0 and 6.0

👀 Global.asax 官網說明 : Global.asax Syntax

👀 Route 路由官網說明 : 終極 ASP.NET: 使用 ASP.NET Web 表單路由



短網址功能實作 :

1. 使用 Nuget 安裝 Microsoft.AspNet.FriendlyUrls 套件 (設定不顯示副檔名用)

https://ithelp.ithome.com.tw/upload/images/20210919/20139487lZ6eccj3mJ.jpg


2. 專案右鍵新增全域應用程式類別 Global.asax

https://ithelp.ithome.com.tw/upload/images/20210919/20139487T2pOM2af3f.jpg

  • 🌵 由於一個專案只會有一個 Global.asax,可以發現如果已新增過,再次右鍵時就無法看到這個選項了。

3. 在 Global.asax 的 Application_Start 事件內加入以下程式碼

protected void Application_Start(object sender, EventArgs e)
{
    // 設定不顯示副檔名 (如果只想隱藏副檔名做到此區塊就好)
    var routes = RouteTable.Routes;
    var settings = new FriendlyUrlSettings();
    settings.AutoRedirectMode = RedirectMode.Permanent;
    routes.EnableFriendlyUrls(settings);

    // 執行短網址路由方法
    RegisterRouters(RouteTable.Routes);
}


4. 在 Global.asax 中建立 RegisterRouters 方法

void RegisterRouters(RouteCollection routes)
{
    // MapPageRoute("自訂路由名稱", "替換後的網址區塊", "原本實際執行的網頁位置")
        // {shortUrl} 為短網址名稱,可以視為之後要用來抓取的參數
    routes.MapPageRoute("shortUrlRoute", "ShowList/{shortUrl}", "~/Tayanahtml/dealers.aspx");
    //可以建立多個規則
}


5. 在想要使用短網址的頁面後置程式碼建立判斷邏輯 (示範頁面 : DEALERS Page)

//取得網址傳值的 id 內容
string urlIDStr = Request.QueryString["id"];

SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["TayanaYachtConnectionString"].ConnectionString);
//如果是用短網址連入則用短網址 shortUrl 參數內容的國家名稱來判斷 ID
if (Page.RouteData.Values.Count > 0) {
    //取得短網址參數內容的國家名稱
    string urlCountryStr = Page.RouteData.Values["shortUrl"].ToString();
    string sqlID = "SELECT id FROM CountrySort WHERE countrySort = @urlCountryStr";
    SqlCommand commandID = new SqlCommand(sqlID, connection);
    commandID.Parameters.AddWithValue("@urlCountryStr", urlCountryStr);
    connection.Open();
    SqlDataReader readerID = commandID.ExecuteReader();
    if (readerID.Read()) {
        urlIDStr = readerID["id"].ToString();
    }
    connection.Close();
}

//如無網址傳值則設為第一筆國家名稱 id
if (string.IsNullOrEmpty(urlIDStr)) {
    string sql = "SELECT TOP 1 id FROM CountrySort";
    SqlCommand command = new SqlCommand(sql, connection);
    connection.Open();
    SqlDataReader reader = command.ExecuteReader();
    if (reader.Read()) {
        urlIDStr = reader["id"].ToString();
    }
    connection.Close();
}

//將 id 存入 Session 使用
Session["id"] = urlIDStr;

//下方依取得 ID 正常進行讀取內容及修改


6. 用短網址連入後會發現圖片掉圖,可依以下方式修改

//原網址-https://localhost:44305/Tayanahtml/dealers?id=1
//短網址-https://localhost:44305/ShowList/USA
//上面兩個網址會得到相同網頁內容

//圖片位置修改方式1 : (用後置程式碼 .aspx.cs 送出 Html 也適用)
<img src="../Tayanahtml/images/newbanner.jpg" />

//圖片位置修改方式2 : (僅 .aspx 頁面適用)
<img src="<%= VirtualPathUtility.ToAbsolute("~/Tayanahtml/images/newbanner.jpg") %>" />

7. 確認不同網址切換都能成功顯示網頁,完成~



本日總結 :

📢 原本是在試 Accupass 設定活動頁面短網址這種活動功能,嘗試去理解它是怎麼做到的,測試成功之後就把它用到專案裡面,算是專案製作的小彩蛋,在新建 Global.asax 檔時,發現預設還有很多種事件可以使用,如果有 Global.asax 相關的應用歡迎留言討論,對應用十分好奇,因為感覺可以做到很多事,感謝!

  • 明日將介紹製作 Dealer Manager - Content Page 後台的相關細節。

上一篇
Day 6 - Using ASHX File for User Authorization Management with ASP.NET Web Forms C# 使用泛型處理常式進行權限分流
下一篇
Day 8 - 依 DEALERS 前台頁面分析拆解後,逐步建立後台功能 (上) - GridView 應用 - ASP.NET Web Forms C#
系列文
ASP.NET Web Forms 入門 - 30天建立遊艇網頁專案後端及後台功能 C#30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 則留言

0
C#.NET
iT邦新手 4 級 ‧ 2021-09-21 13:14:44

酷!!!

2
小朱
iT邦新手 4 級 ‧ 2021-09-21 20:07:25

.aspx內的解網址不要使用 Page.ResolveUrl(),已經被證實有資安風險。
請改用 VirtualPathUtility.ToAbsolute()

龜人 iT邦新手 3 級 ‧ 2021-09-21 21:21:52 檢舉

感謝提醒!!已爬文修正!!/images/emoticon/emoticon41.gif

我要留言

立即登入留言