ASP.NET取值高效方法全解析 | 如何在ASP.NET中取值,ASP.NET开发技巧
- 技术教程
- 2026-02-08
- 4200
在 ASP.NET 中,根据不同的场景(如 Web Forms、MVC、Core 等)和数据类型(QueryString、Form、Session 等),取值方式有所不同,以下是常见场景的取值方法:
ASP.NET Web Forms 取值
-
获取 QueryString 值
URL 示例:page.aspx?id=123
string id = Request.QueryString["id"]; // 返回 "123" -
获取 Form 表单值
string username = Request.Form["txtUsername"]; // 通过表单控件 name 获取 -
获取控件值(服务端控件)
// 假设页面上有 <asp:TextBox ID="txtName" runat="server" /> string name = txtName.Text; // 直接访问控件属性 -
获取 Session 值
// 存值 Session["UserID"] = "1001"; // 取值(需类型转换) string userId = Session["UserID"]?.ToString(); int id = Convert.ToInt32(Session["UserID"]);
-
获取 Cookie 值
// 存值 Response.Cookies["Theme"].Value = "Dark"; // 取值 string theme = Request.Cookies["Theme"]?.Value;
ASP.NET MVC 取值
-
Action 参数自动绑定
// URL: /user/profile?id=100 public ActionResult Profile(int id) // 自动绑定到 id { // 直接使用 id }
-
通过 FormCollection 获取表单数据
-
模型绑定(推荐方式)
public class User { public string Name { get; set; } public int Age { get; set; } } [HttpPost] public ActionResult Create(User user) // 自动绑定到模型 { string name = user.Name; }
-
获取 QueryString / RouteData
// URL: /product/details/5 public ActionResult Details() { int id = Convert.ToInt32(RouteData.Values["id"]); string category = Request.QueryString["category"]; } -
控制器参数绑定
-
手动获取请求数据
public IActionResult Index() { // 获取 QueryString var id = HttpContext.Request.Query["id"].ToString(); // 获取 Form 数据 if (Request.HasFormContentType) var name = Request.Form["name"].ToString(); }
-
从路由获取数据
[Route("user/{id}")] public IActionResult Profile(string id) // id = 路由值 { }
-
读取配置 appsettings.json
// 在 Startup.cs 载入配置 public void ConfigureServices(IServiceCollection services) { var configValue = Configuration["AppSettings:ApiKey"]; } -
类型安全转换
使用 int.TryParse() 或 Convert 类避免异常:
if (int.TryParse(Request.QueryString["id"], out int id)) { /* 安全使用 id */ } -
空值处理
使用 操作符防止空引用:
string role = Session["Role"]?.ToString() ?? "Guest"; -
跨平台请求数据获取(.NET Core)
// 统一获取请求值(支持 GET/POST) var value = Request.HttpContext.Request.Query["key"].FirstOrDefault() ?? Request.HttpContext.Request.Form["key"].FirstOrDefault(); - 安全性:对用户输入进行验证(如 ModelState.IsValid 在 MVC 中)。
- 编码:防止 XSS 攻破,对输出内容进行编码(@Html.Encode() 或 HttpUtility.HtmlEncode())。
- Session 状态:在 Core 中需在 Startup.cs 启用 services.AddSession() 和 app.UseSession()。
ASP.NET Core 取值
通用技巧
注意事项
根据您的具体场景选择合适的取值方式,并始终注意数据安全和类型转换的健壮性。