ASP.NET MVC Controller Context
2023-08-22
筆記關於 ASP.NET MVC 5 Controller 可以調用的各式 Property,用以存取 Request, Route, HttpContext, User, TempData 等的資訊 😙
 
說明
| Property | Type | Description | 
|---|---|---|
| Request.QueryString | NameValueCollection | 儲存 URL 查詢字串參數,從 URL 中擷取參數值 | 
| Request.ServerVariables | NameValueCollection | 包含伺服器相關的變數,如 HTTP 標頭和伺服器路徑 | 
| Request.Form | NameValueCollection | 存取 POST 資料,例如表單提交的數據 | 
| Request.Headers | NameValueCollection | 儲存 HTTP 請求的標頭信息,如 User-Agent 和 Content-Type | 
| Request.Params | NameValueCollection | 包含請求中的所有參數,包括 QueryString、Form 和 Cookies | 
| Request.Cookies | HttpCookieCollection | 處理客戶端傳遞的 cookie 資訊 | 
| Request.HttpMethod | string | 表示 HTTP 請求方法,如 GET、POST 等 | 
| Request.Url | Uri | 包含完整的請求 URL 資訊,可獲取主機、路徑等資訊 | 
| Request.UserHostAddress | string | 獲取用戶端的 IP 位址,識別訪問者 | 
| RouteData.Route | RouteBase | 表示處理請求的路由配置 | 
| RouteData.Values | RouteValueDictionary | 儲存路由中的參數值,如 Controller、Action 等 | 
| HttpContext.Application | HttpApplicationState | 提供應用程式級別的全域變數,供所有用戶共享 | 
| HttpContext.Cache | Cache | 快取資料,提升應用程式的效能 | 
| HttpContext.Items | IDictionary | 允許在同一個 HTTP 請求的多個部分間共享資料 | 
| HttpContext.Session | HttpSessionStateBase | 提供用戶特定的會話資料儲存,跨頁面保持狀態 | 
| User | IPrincipal | User 的安全性和識別信息 | 
| TempData | TempDataDictionary | 臨時儲存在連續請求間共用的資料 | 
另外也可以藉由以下 Code,顯示所有的 Property Name, Type 以及 Value:
Controller.cs
public ActionResult CustomServerInfo()
{
    var propertyTypes = new Dictionary<string, Dictionary<string, Tuple<Type, object>>>();
    foreach (var current in new List<object> { 
        Response, Request, HttpContext, RouteData, User, TempData, ViewBag, Session, HttpContext.Application,
        User.Identity, Request.Cookies.AllKeys, Request.ServerVariables.AllKeys })
    {
        var tempDict = new Dictionary<string, Tuple<Type, object>>();
        PropertyInfo[] properties = current.GetType().GetProperties();
        foreach (PropertyInfo property in properties)
        {
            if (property.Name != "Item")
            {
                tempDict.Add(property.Name, new Tuple<Type, object>(property.PropertyType, property.GetValue(current, null)));
            }
        }
        propertyTypes[current.GetType().Name] = tempDict;
    }
    return View(propertyTypes);
}View.cshtml
@model Dictionary<string, Dictionary<string, Tuple<Type, object>>>
@{
    ViewBag.Title = "CustomServerInfo";
}
@foreach (var current in Model)
{
<h2>
    @current.Key
</h2>
<table class="table table-bordered">
    <tr>
        <th>Key</th>
        <th>Type</th>
        <th>Value</th>
    </tr>
    @foreach (var property in current.Value)
    {
        <tr>
            <td>@property.Key</td>
            <td class="@(property.Value.Item1.ToString() == "System.String" ? "text-primary" : "")">
                @property.Value.Item1
            </td>
            <td>@property.Value.Item2</td>
        </tr>
    }
</table>
}