052 模型验证(Model Validation)介绍

本文介绍了在ASP.NETCore中使用DataAnnotations进行模型验证的基本步骤,包括创建Person类、设置DataAnnotations属性、以及在Controller中处理POST请求时的预期错误处理。作者展示了如何在Postman中测试验证并指出缺少错误提示的问题。
摘要由CSDN通过智能技术生成

语法

示例

新建一个ASP.NET Core Empty项目,项目名称ModelValidationsExample

Program.cs中代码如下

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();

//app.MapGet("/", () => "Hello World!");

app.UseStaticFiles();
app.UseRouting();
app.MapControllers();

app.Run();

新建文件夹Models,在此文件夹下新建类Person.cs

public class Person
{
    public Guid PersonId { get; set; }
    public string? PersonName { get; set; }
    public string? Email { get; set; }
    public string? Phone { get; set; }
    public string? Password { get; set; }
    public string? ConfirmPassword { get; set; }
    public double? Price { get; set; }

    public override string ToString()
    {
        return $"Person object - PersonName: {PersonName}, Email: {Email}, " +
            $"Phone: {Phone}, Password: {Password}, ConfirmPassword: {ConfirmPassword}, Price: {Price} ";
    }
}

新建文件夹Controllers,在此文件夹下新建Controller HomeController.cs

public class HomeController : Controller
{
    [Route("register")]
    public IActionResult Index(Person person)
    {
        return Content($"{person}");
    }
}

DataAnnotations(数据注释)验证数据合理性

[Required]
public string? PersonName { get; set; }

Postman中发送数据给服务器,不勾选PersonName或者删除Value

正常情况这个时候应该有个报错,但是这里没有报错,关于如何报错,下一节继续讲解。

模型验证过程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黄健华Yeah

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值