ASP.NET Web Pages(Razor)中最常用的内置对象全解析
(2025 年依然是开发者的“瑞士军刀”)
在 .cshtml 页面里,你可以直接使用下面这些对象,不需要任何 using 或实例化,它们永远都在!
| 对象 | 类型 | 常用属性/方法 | 典型用途举例 |
|---|---|---|---|
| Request | HttpRequestBase | Request["name"]、.QueryString、.Form、.Files、.Url、.UserHostAddress | 取表单值、GET 参数、上传文件、获取 IP |
| Response | HttpResponseBase | Response.Write()、.Redirect()、.SetCookie()、.StatusCode | 跳转页面、写内容、设置 Cookie、返回 404 |
| Session | HttpSessionStateBase | Session["UserId"]=123、.Timeout、.Abandon() | 保存登录状态、购物车、临时数据 |
| Application | HttpApplicationStateBase | Application["OnlineCount"]++、.Lock()/.UnLock() | 全站共享数据、在线人数统计 |
| Server | HttpServerUtilityBase | Server.MapPath("~/App_Data")、.HtmlEncode()、.UrlEncode() | 路径转换、HTML 编码、防注入 |
| Cache | Cache | Cache["key"]=value、.Insert()、.Remove() | 全站缓存(比 Session 更快、更省内存) |
| Page | WebPageBase | Page.Title、Page.Layout、Page.PageData | 设置标题、布局、跨页面传值 |
| PageData | DynamicDictionary | PageData["User"]=user、PageData[0]="hello" | 页面间传值(比 ViewBag 更强大) |
| Context | HttpContextBase | Context.User.Identity.Name、.Items | 获取当前登录用户、Request-级别临时存储 |
| UrlData | List | UrlData[0] | 友好 URL 路由参数(如 /Products/123 → UrlData[0]=”123″) |
| ModelState | ModelStateDictionary | ModelState.AddError()、.IsValid | 服务端表单验证 |
| Validation | ValidationHelper | Validation.RequireField()、.IsValid() | 最简洁的验证方式 |
| WebSecurity | WebMatrix.WebData | WebSecurity.CurrentUserId、.Login()、.ChangePassword() | 会员系统核心对象 |
| Roles | WebMatrix.WebData | Roles.IsUserInRole("Admin")、.GetRolesForUser() | 角色权限控制 |
| Database | WebMatrix.Data | Database.Open("MyDB")、.Query()、.Execute() | 最轻量数据库操作(SQL CE/SQL Server) |
| File | WebMatrix.WebData.FileHelper | File.Upload()、.Exists()、.Delete() | 文件上传(旧版方式,新版推荐 Request.Files) |
| AntiForgery | AntiForgery | AntiForgery.GetHtml()、.Validate() | 防止 CSRF 攻击(表单必加) |
| Href | 内置函数 | @Href("~/Admin/Index.cshtml") → /Admin/Index.cshtml | 生成正确根路径 |
| IsPost / IsAjax | bool | if(IsPost){...}、if(IsAjax){...} | 判断请求方式 |
实战中最常用的 10 行代码(背会就无敌)
@{
var name = Request["name"]; // 1. 取表单或 QueryString
var file = Request.Files["avatar"]; // 2. 取上传文件
var userId = Session["UserId"]?.ToString(); // 3. 登录状态
Session["LastVisit"] = DateTime.Now; // 4. 记录最后访问时间
Application.Lock();
Application["OnlineCount"] = (int)(Application["OnlineCount"]??0) + 1;
Application.UnLock(); // 5. 在线人数 +1
var physicalPath = Server.MapPath("~/uploads/"); // 6. 服务器真实路径
Response.Redirect("~/Admin/"); // 7. 页面跳转
Cache.Insert("SiteConfig", config, null,
DateTime.Now.AddHours(1), Cache.NoSlidingExpiration); // 8. 缓存1小时
PageData["Title"] = "用户中心"; // 9. 传值给 Layout
Page.Title = "欢迎 " + WebSecurity.CurrentUserName; // 10. 动态标题
}
经典综合示例(一个页面用到了 12 个对象)
<!-- User/Profile.cshtml -->
@{
Layout = "~/Shared/_Layout.cshtml";
Page.Title = "个人资料";
var userId = WebSecurity.CurrentUserId; // WebSecurity
var user = Database.Open("MySite") // Database
.QuerySingle("SELECT * FROM Users WHERE Id=@0", userId);
if (IsPost) { // IsPost
AntiForgery.Validate(); // AntiForgery
var avatar = Request.Files["avatar"]; // Request.Files
if (avatar != null && avatar.ContentLength > 0) {
var savePath = Server.MapPath("~/Uploads/Avatar/");
var fileName = userId + Path.GetExtension(avatar.FileName);
avatar.SaveAs(savePath + fileName);
// 更新数据库
Database.Open("MySite").Execute(
"UPDATE Users SET Avatar=@0 WHERE Id=@1",
"/Uploads/Avatar/" + fileName, userId);
}
Response.Redirect("~/User/Profile.cshtml?saved=1"); // Response
}
// 记录访问日志(Application + Cache)
var logKey = "ProfileViews_" + DateTime.Today.ToString("yyyyMMdd");
Cache[logKey] = (Cache[logKey] as int? ?? 0) + 1;
}
<h2>欢迎,@user.UserName</h2>
<img src="@user.Avatar" width="120" /><br>
<form method="post" enctype="multipart/form-data">
@AntiForgery.GetHtml()
更换头像:<input type="file" name="avatar" />
<button type="submit">保存</button>
</form>
<p>今日个人中心访问量:@(Cache[logKey] as int? ?? 0) 次</p>
终极记忆口诀(10 个字记住全部核心对象)
请回会话应服缓页数防
Request → Response → Session → Application → Cache → Server → Page → Database → WebSecurity → AntiForgery
只要记住这 10 个对象,你写 ASP.NET Web Pages 就再也没有“不知道用哪个”的困扰了!
需要我给你一个“所有对象一键演示”的完整项目吗?一个页面里把上面所有对象都用一遍,边看边学,3 分钟掌握 90% 的核心 API。随时说一声就发你!