通过 URL 查询字符串 传递参数
这是最常见的方式,格式为 https://example.com/page?key1=value1&key2=value2。

ASP.NET Web Forms
在 Web Forms 中,你可以通过 Request.QueryString 集合来获取。
示例:
URL: https://example.com/Default.aspx?name=张三&age=25
在 Default.aspx.cs 后台代码中:
protected void Page_Load(object sender, EventArgs e)
{
// 检查参数是否存在,避免空引用异常
string name = Request.QueryString["name"];
int age = 0;
// 尝试将年龄参数转换为整数
if (int.TryParse(Request.QueryString["age"], out age))
{
// 成功获取参数
Response.Write($"你好, {name}! 你今年 {age} 岁。");
}
else
{
// 参数不存在或格式不正确
Response.Write("年龄参数无效或未提供。");
}
}
ASP.NET MVC / ASP.NET Core MVC
在 MVC 中,通常通过 Action 方法的参数来直接接收,ASP.NET 的模型绑定机制会自动完成这个工作。

示例:
URL: https://example.com/Home/Welcome?name=李四&age=30
在 HomeController.cs 中:
public class HomeController : Controller
{
public IActionResult Welcome(string name, int age)
{
// Action 方法直接定义了参数,框架会自动从 QueryString 中填充
// 如果参数缺失或类型不匹配,name 会是 null, age 会是 0
if (!string.IsNullOrEmpty(name))
{
ViewData["Message"] = $"你好, {name}! 你今年 {age} 岁。";
}
else
{
ViewData["Message"] = "请提供姓名参数。";
}
return View();
}
}
更优雅的方式:使用 ViewModel 当参数较多时,推荐使用一个 ViewModel 类来封装所有参数,代码更清晰。
ViewModel:

public class WelcomeViewModel
{
public string Name { get; set; }
public int Age { get; set; }
}
Controller:
public IActionResult Welcome(WelcomeViewModel model)
{
// 模型绑定会自动将 QueryString 的值映射到 ViewModel 的属性上
if (ModelState.IsValid) // 可以进行数据验证
{
ViewData["Message"] = $"你好, {model.Name}! 你今年 {model.Age} 岁。";
}
return View();
}
通过 HTML 表单 (Form) POST 传递参数
这是在用户提交表单时最常用的方式,数据在 HTTP 请求体中发送。
ASP.NET Web Forms
与 QueryString 类似,使用 Request.Form 集合。
HTML (Default.aspx):
<form action="Default.aspx" method="post">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" value="登录" />
</form>
后台代码 (Default.aspx.cs):
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack) // 确保是表单提交后执行
{
string username = Request.Form["username"];
string password = Request.Form["password"];
Response.Write($"你提交的用户名是: {username}");
}
}
ASP.NET MVC / ASP.NET Core MVC
同样是利用 Action 方法的参数和模型绑定机制。
HTML (Welcome.cshtml):
<form asp-action="Welcome" method="post">
<input type="text" name="name" />
<input type="number" name="age" />
<input type="submit" value="提交" />
</form>
Controller (HomeController.cs):
[HttpPost] // 明确指定这个 Action 只处理 POST 请求
public IActionResult Welcome(string name, int age)
{
// 模型绑定会自动从 Form 中填充参数
ViewData["Message"] = $"你好, {name}! 你今年 {age} 岁。";
return View();
}
同样,也推荐使用 ViewModel。
通过 URL 路由 传递参数
这是 MVC 和 Core MVC 中更现代、更优雅的方式,参数是 URL 路径的一部分。
示例:
URL: https://example.com/Users/Detail/123
这里的 123 是用户ID,而不是查询字符串。
ASP.NET MVC / ASP.NET Core MVC
这需要配置路由规则和相应的 Action 方法。
配置路由 (Startup.cs 或 RouteConfig.cs)
默认的路由模板已经支持这种模式:{controller=Home}/{action=Index}/{id?}。
{id?} 中的 表示 id 是可选的。
编写 Action 方法
Controller 中的参数名必须与路由模板中的占位符名(这里是 id)匹配。
public class UsersController : Controller
{
// 访问 /Users/Detail/123 时,123 会自动传递给 userId 参数
public IActionResult Detail(int userId)
{
// 根据userId从数据库获取用户信息...
// var user = _userService.GetUserById(userId);
ViewData["UserId"] = userId;
return View();
}
}
通过 HTTP 请求体 传递 JSON 数据 (AJAX/API)
在现代 Web 应用中,前后端分离架构非常流行,前端通过 AJAX 发送 JSON 数据,后端接收并反序列化为对象。
示例:
前端使用 fetch 发送一个 JSON 对象 { "name": "王五", "age": 40 }。
ASP.NET Core MVC (推荐方式)
这是 Core 处理 JSON 的标准方式,非常强大。
Controller:
using Microsoft.AspNetCore.Mvc; // 确保引用
[ApiController] // 使用 [ApiController] 特性可以自动处理模型绑定和验证
[Route("api/[controller]")]
public class PeopleController : ControllerBase
{
[HttpPost("welcome")]
public IActionResult Welcome([FromBody] WelcomeViewModel model)
{
// [FromBody] 特性告诉框架从请求体中读取数据并尝试反序列化为 WelcomeViewModel
// JSON 格式不匹配或数据无效,ModelState.IsValid 会为 false
if (ModelState.IsValid)
{
// 处理接收到的数据
return Ok(new { Message = $"你好, {model.Name}! 你今年 {model.Age} 岁。" });
}
// 如果模型验证失败,返回 400 Bad Request 错误
return BadRequest(ModelState);
}
}
ViewModel (同上):
public class WelcomeViewModel
{
// 可以添加数据验证特性
[Required(ErrorMessage = "姓名是必填项")]
public string Name { get; set; }
[Range(1, 120, ErrorMessage = "年龄必须在1到120之间")]
public int Age { get; set; }
}
ASP.NET Web API (旧版,基于 .NET Framework)
Web API 的方式与 Core 类似,但语法略有不同。
public class PeopleController : ApiController
{
[HttpPost]
public IHttpActionResult Welcome(WelcomeViewModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// 处理数据...
return Json(new { Message = $"你好, {model.Name}! 你今年 {model.Age} 岁。" });
}
}
在 Web API 中,[FromBody] 也是可选的,但明确写上是更好的实践。
总结与最佳实践
| 技术栈 | 参数类型 | 接收方式 | 备注 |
|---|---|---|---|
| Web Forms | Query String | Request.QueryString["key"] |
基础、直接,但容易出错,缺乏类型安全。 |
| Form POST | Request.Form["key"] |
同上。 | |
| MVC / Core MVC | Query String / Form POST | Action 参数 / ViewModel | 推荐,利用模型绑定,代码简洁、类型安全。 |
| Route Data | Action 参数 (需匹配路由占位符) | 推荐,URL 更美观,RESTful 风格。 | |
| JSON (AJAX) | Action 参数 + [FromBody] 特性 + ViewModel |
API 开发标准,前后端分离首选,支持复杂对象和验证。 |
核心建议:
- 优先使用 MVC/Core MVC 模式:相比 Web Forms,它提供了更结构化、更安全、更易于维护的代码。
- 拥抱模型绑定:尽量使用 Action 方法的参数或 ViewModel 来接收数据,而不是直接使用
Request对象,这能让你的代码更清晰,也更容易进行单元测试。 - 为 API 使用 JSON:在开发 Web API 或与前端进行数据交互时,始终使用
[FromBody]和 ViewModel 来接收 JSON 数据。 - 总是进行验证:使用
[Required],[Range]等数据注解特性来验证输入数据的有效性,防止无效或恶意数据进入你的系统。
