ASP.NET Core MVC 模型绑定 (转载)
ASP.NET Core MVC的Model Binding会将HTTP Request数据,以映射的方式对应到参数中。基本上跟ASP.NET MVC差不多,但能Binding的来源更多了一些。
本篇将介绍ASP.NET Core的Model Binding。
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
透过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。
如果三者都传入的话,会依照优先顺序取值Form > Route > Query。
Binding Attributes
除了预设的三种Binding 来源外,还可以通过Model Binding Attributes 从HTTP Request 的其他数据中Binding。有以下6 种:
- [FromHeader]
从HTTP Header取值。
- [FromForm]
通过HTTP POST的form取值。
- [FromRoute]
是通过MVC Route URL取值。
- [FromQuery]
是通过URL Query参数取值。
- [FromBody]
从HTTP Body取值,通常用于取JSON, XML。
ASP.NET Core MVC预设的序列化是使用JSON,如果要传XML格式做Model Binding的话,要在MVC服务加入XmlSerializerFormatters,如下:
Startup.cs
// ...
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddXmlSerializerFormatters();
}
- [FromServices]
这个比较特别,不是从HTTP Request取值,而是从DI容器取值。
DI预设是使用Constructor Injection,但Controller可能会因为每个Action用到不一样的Service导致很多参数,所以也可以在Action注入Service。
范例程序
// ...
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
logger is null: False.
BodySample输出结果:
- JSON

- XML

Model 验证
Model Binding 也可以顺便帮忙验证字段数据,只要在字段的属性上面带上Validation Attributes,如下:
using System.ComponentModel.DataAnnotations;
// ...
public class UserModel
{
[Required]
public int Id { get; set; } [RegularExpression(@"\w+")]
[StringLength(, MinimumLength = )]
public string Name { get; set; } [EmailAddress]
public string Email { get; set; } [Phone]
public string PhoneNumber { get; set; } [StringLength()]
public string Address { get; set; }
}
然后在Action 加上判断:
Controllers\HomeController.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 < )
{
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";
}
}
}
参考
Overview of ASP.NET Core MVC
Introduction to model validation in ASP.NET Core MVC
ASP.NET CORE 2.0 MVC MODEL BINDING
ASP.NET CORE 2.0 MVC MODEL VALIDATION
ASP.NET Core MVC 模型绑定 (转载)的更多相关文章
- ASP.NET Core MVC 模型绑定用法及原理
前言 查询了一下关于 MVC 中的模型绑定,大部分都是关于如何使用的,以及模型绑定过程中的一些用法和概念,很少有关于模型绑定的内部机制实现的文章,本文就来讲解一下在 ASP.NET Core MVC ...
- .net core mvc 模型绑定 之 json and urlencoded
.net core mvc 模型绑定, FromQuery,对应 url 中的 urlencoded string ("?key1=value1&key2=value2") ...
- ASP.NET Core 中文文档 第四章 MVC(01)ASP.NET Core MVC 概览
原文:Overview of ASP.NET Core MVC 作者:Steve Smith 翻译:张海龙(jiechen) 校对:高嵩 ASP.NET Core MVC 是使用模型-视图-控制器(M ...
- ASP.NET Core MVC 概述
https://docs.microsoft.com/zh-cn/aspnet/core/mvc/overview?view=aspnetcore-2.2 ASP.NET Core MVC 概述 20 ...
- 你所不知道的ASP.NET Core MVC/WebApi基础系列(二)
前言 好久没冒泡了,算起来估计有快半年没更新博客了,估计是我第一次停更如此之久,人总有懒惰的时候,时间越长越懒惰,但是呢,不学又不行,持续的惰性是不行dei,要不然会被时光所抛弃,技术所淘汰,好吧,进 ...
- 你所不知道的ASP.NET Core MVC/WebApi基础系列 (二)
转自博客:https://www.cnblogs.com/CreateMyself/p/10604293.html 前言 本节内容,我们来讲讲.NET Core当中的模型绑定系统.模型绑定原理.自定义 ...
- ASP.NET Core 入门教程 3、ASP.NET Core MVC路由入门
一.前言 1.本文主要内容 ASP.NET Core MVC路由工作原理概述 ASP.NET Core MVC带路径参数的路由示例 ASP.NET Core MVC固定前/后缀的路由示例 ASP.NE ...
- ASP.NET Core 入门笔记4,ASP.NET Core MVC路由入门
敲了一部分,懒得全部敲完,直接复制大佬的博客了,如有侵权,请通知我尽快删除修改 摘抄自https://www.cnblogs.com/ken-io/p/aspnet-core-tutorial-mvc ...
- ASP.NET Core MVC/WebAPi 模型绑定探索 转载https://www.cnblogs.com/CreateMyself/p/6246977.html
前言 相信一直关注我的园友都知道,我写的博文都没有特别枯燥理论性的东西,主要是当每开启一门新的技术之旅时,刚开始就直接去看底层实现原理,第一会感觉索然无味,第二也不明白到底为何要这样做,所以只有当你用 ...
随机推荐
- jsp登录显示
1.登录成功设置session request.getSession().setAttribute("user", user); 2.前台test <div class=&q ...
- 如何在PeopleSoft中找到并更改默认样式表名称
PeopleSoft的默认样式表名称是用来控制应用程序的外观的.在PeopleSoft中可以使用集中样式表来更改应用程序的外观,oracle为每个应用程序版本设置了默认的样式表. 下面是不同应用程序版 ...
- arm64 调试环境搭建及 ROP 实战
前言 比赛的一个 arm 64 位的 pwn 题,通过这个题实践了 arm 64 下的 rop 以及调试环境搭建的方式. 题目文件 https://gitee.com/hac425/blog_data ...
- Expo大作战(三)--针对已经开发过react native项目开发人员有针对性的介绍了expo,expo的局限性,开发时项目选型注意点等
简要:本系列文章讲会对expo进行全面的介绍,本人从2017年6月份接触expo以来,对expo的研究断断续续,一路走来将近10个月,废话不多说,接下来你看到内容,讲全部来与官网 我猜去全部机翻+个人 ...
- sudo控制权限简单用法介绍
为了安全及管理的方便,可将需要用root权限的用户加入到sudo管理,用root的权限来管理系统.利用sudo控制用户对系统命令的使用权限. 普通用户可以查看,但不能删除: 但是在/tmp公共环境下可 ...
- python 多进程和子进程1
多进程的缓冲区 #多进程 process.py from multiprocessing import Process,current_process import time def func1(): ...
- Java 中File类的createNewFile()与createTempFile(), delete和deleteOnExit区别
1. Java 中File类的createNewFile()与createTempFile()的区别 最近,在看代码时看到了一个方法, File.createTempFile() ,由此联想到File ...
- 【待补充】[Linux] nc
[nc 是做什么的] [nc怎么用] 查看帮助 nc -help # 查看帮助 nc -help # 监听端口 -l, --listen Bind and listen for incoming co ...
- 【转】Linxu学习---top实践
[原文]https://www.toutiao.com/i6591053058258502147/ 在实际开发中,有时候会收到一些服务的监控报警,比如CPU飙高,内存飙高等,这个时候,我们会登录到服务 ...
- fedora27安装后的配置工作(持续更新)
换源 没什么可说的,安装后更换国内软件源是必须做的事,推荐更换阿里的镜像源.换源教程 添加epel源 EPEL (Extra Packages for Enterprise Linux)是基于Fedo ...