在 ASP.NET 中,根据不同的场景(如 Web Forms、MVC、Core 等)和数据类型(QueryString、Form、Session 等),取值方式有所不同,以下是常见场景的取值方法:

ASP.NET Web Forms 取值
-
获取 QueryString 值
URL 示例:page.aspx?id=123string 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 获取表单数据
[HttpPost] public ActionResult Submit(FormCollection form) { string email = form["Email"]; } -
模型绑定(推荐方式)
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"]; }
ASP.NET Core 取值
-
控制器参数绑定
// 查询字符串:/product?id=5 public IActionResult Detail(int id) { /* 自动绑定 */ } // 表单提交 [HttpPost] public IActionResult Create([FromForm] Product model) { } -
手动获取请求数据
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()。
根据您的具体场景选择合适的取值方式,并始终注意数据安全和类型转换的健壮性。
图片来源于AI模型,如侵权请联系管理员。作者:酷小编,如若转载,请注明出处:https://www.kufanyun.com/ask/287218.html

