1.参数
HttpRequest
HttpRequest
是用户请求对象
QueryString
Form
Cookie
Session
Header
实例:
public IActionResult Index()
{
QueryString x = Request.QueryString; // ?a=1
string x = Request.Query["a"]; //1
return View();
}
HttpContext
HttpContext
是用户请求上下文
提供Session属性获取Session对象
Session.Set
设置
Session.Remove
移除
Session.TryGetValue
获取数据
2.数据绑定
2.1.Model Binding
要接收Client 传送来的数据,可以通过Action 的参数接收,如下:
using Microsoft.AspNetCore.Mvc;
namespace MyWebsite.Controllers
{
public class HomeController : Controller
{
public IActionResult Index(int id)
{
return Content($"id: {id}");
}
}
}
id就是从HTTP Request的内容被Binding的Model参数。
预设的Model Binding会从HTTP Request的三个地方取值(优先顺序由上到下):
如果三者都传入的话,会依照优先顺序取值Form > Route > Query
。
- Form
透过HTTP POST的form取值。如下图:
- Route
是通过MVC Route URL取值。
如:http://localhost:5000/Home/Index/2,id取出的值就会是2。 - Query
是通过URL Query参数取值。
如:http://localhost:5000/Home/Index?id=1,id取出的值就会是1。
2.2.Attribute Binding
默认绑定方式,使用特性:
[FromBody] 请求体
[FromHeader] headers
[FromQuery] 查询字符串
[FromRoute] 路由数据
[FromForm] 表单数据
[FromServices] 服务注册
示例1 FromHeader
前台:
<div style="height:100px">
<input type="button" value="提交带header参数" onclick="save()" />
</div>
<script>
function save() {
$.ajax({
url: "home/index",
beforeSend: function (xhr) {
xhr.setRequestHeader("username", "tangsansan");
},
type:"post",
success: function(data) {
}
});
}
</script>
后台:
public IActionResult Index([FromHeader] string username)
{
QueryString x = Request.QueryString;
return View();
}
示例2
public class HomeController : Controller
{
public IActionResult FirstSample(
[FromHeader]string header,
[FromForm]string form,
[FromRoute]string id,
[FromQuery]string query)
{
return Content($"header: {header}, form: {form}, id: {id}, query: {query}");
}
public IActionResult DISample([FromServices] ILogger<HomeController> logger)
{
return Content($"logger is null: {logger == null}.");
}
public IActionResult BodySample([FromBody]UserModel model)
{
return Ok(model);
}
}
// ...
public class UserModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public string Address { get; set; }
}
输出结果
FirstSample输出结果:
DISample输出结果:
http://localhost:5000/Home/DISample
BodySample输出结果:
- JSON
- XML
3.模型验证
Model Binding 也可以顺便帮忙验证字段数据,只要在字段的属性上面带上Validation Attributes,如下:
using System.ComponentModel.DataAnnotations;
// ...
public class UserModel
{
[Required]
public int Id { get; set; }
[RegularExpression(@"w+")]
[StringLength(20, MinimumLength = 4)]
public string Name { get; set; }
[EmailAddress]
public string Email { get; set; }
[Phone]
public string PhoneNumber { get; set; }
[StringLength(200)]
public string Address { get; set; }
}
然后在Action 加上判断:
ControllersHomeController.cs
using Microsoft.AspNetCore.Mvc;
namespace MyWebsite.Controllers
{
public class HomeController : Controller
{
// ...
public IActionResult BodySample([FromBody]UserModel model)
{
// 由于 Id 是 int 类型,int 默认为 0
// 虽然带上了 [Required],但不是 null 所以算是有值。
if (model.Id < 1)
{
ModelState.AddModelError("Id", "Id not exist");
}
if (ModelState.IsValid)
{
return Ok(model);
}
return BadRequest(ModelState);
}
}
}
.NET Core提供了很多的Validation Attributes,可以参考官网 System.ComponentModel.DataAnnotations
自定义Validation Attributes
如果.NET Core提供的Validation Attributes不够用还可以自己做。
例如上述范例的数据模型多了生日字段,需要验证年龄:
using System;
using System.ComponentModel.DataAnnotations;
namespace MyWebsite.Attributes
{
public class AgeCheckAttribute : ValidationAttribute
{
public int MinimumAge { get; private set; }
public int MaximumAge { get; private set; }
public AgeCheckAttribute(int minimumAge, int maximumAge)
{
MinimumAge = minimumAge;
MaximumAge = maximumAge;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var date = Convert.ToDateTime(value);
if (date.AddYears(MinimumAge) > DateTime.Today
|| date.AddYears(MaximumAge) < DateTime.Today)
{
return new ValidationResult(GetErrorMessage(validationContext));
}
return ValidationResult.Success;
}
private string GetErrorMessage(ValidationContext validationContext)
{
// 有帶 ErrorMessage 的话优先使用
// [AgeCheck(18, 120, ErrorMessage="xxx")]
if (!string.IsNullOrEmpty(this.ErrorMessage))
{
return this.ErrorMessage;
}
// 自定义错误信息
return $"{validationContext.DisplayName} can't be in future";
}
}
}
参考:
snailteam,ASP.NET Core 2 学习笔记(九)模型绑定