zl程序教程

您现在的位置是:首页 >  其它

当前栏目

一、模型验证CoreWebApi 管道方式(非过滤器处理)

处理 方式 模型 验证 过滤器 管道
2023-09-11 14:19:05 时间

一、新建.Net Core的MVC项目添加WebApi控制器的方式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace TempTest.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class VerifController : ControllerBase
    {
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

    }
}

 http://localhost:60748/api/Verif/Get 访问不通   http://localhost:60748/api/Verif 才可以

 我新建core的空的webapi为

我们更改

 [Route("api/[controller]/[action]")]
 [ApiController]
 public class HomeController : ControllerBase

即:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace TempTest.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class VerifController : ControllerBase
    {
        [HttpPost]
        public DateTime GetDates() //api自定义类型,指定时间类型吧
        {
            return DateTime.Now;
        }
    }
}

 //

http://localhost:60748/api/Verif/GetDates

//

 

区别:不想iFramework mvc 那样创建webapi 需要配置 api路由,(而且创建空的WebApi控制器并不友好,不指定具体的action,还需要我主动添加)

二、添加到管道

Startup.cs

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            //模型绑定 特性验证,自定义返回格式 
            //->必须放在 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);后面,
            //因为走过路由控制器,才可以知道控制器里面对参数格式的验证
            services.Configure<ApiBehaviorOptions>(options =>
            {
                options.InvalidModelStateResponseFactory = actionContext =>
                {
                    //获取验证失败的模型字段 
                    var errors = actionContext.ModelState
                    .Where(e => e.Value.Errors.Count > 0)
                    .Select(e => e.Value.Errors.First().ErrorMessage)
                    .ToList();
                    var str = string.Join("|", errors);
                    //设置返回内容
                    var result = new
                    {
                        code = 12001,
                        body = false,
                        msg = str
                    };
                    return new BadRequestObjectResult(result);
                };
            });
        }

Model验证实体

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace WebApi.Models
{
    public class Personnel
    {
        [Required(ErrorMessage = "Name参数不能为空")]//Required 验证这个参数不能为空 ErrorMessage:为空时自定义错误信息
        public string Name { get; set; }
        [Required(ErrorMessage = "Age参数不能为空")]
        [Range(1, 100, ErrorMessage = "Age参数只能是大于1,小于100")]//Range 验证值只能在某些范围内,只适用于Int类型的字段
        public int Age { get; set; }

        [Required(ErrorMessage = "电话号不能为空")]
        [RegularExpression("^[1]+[3,4,5,7,8]+\\d{9}", ErrorMessage = "PhoneNum不合法的电话号码格式")]//RegularExpression 用正则验证字段的合法性,多用于身份证、电话号码、邮箱、等等...
        public string PhoneNum { get; set; }
    }
}

控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using TempTest.Models;

namespace TempTest.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class VerifController : ControllerBase
    {
        [HttpPost]
        public DateTime GetDates(Personnel personnel) //api自定义类型,指定时间类型吧
        {
            return DateTime.Now;
        }
    }
}

必须Raw方式提交,且数据格式为Json

最终效果:

Ajax测试就不支持Post提交的Row方式

换种方式实现:

1、model

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace TempTest.Models
{
    public class UserModel
    {
        [Required(ErrorMessage = "名字不能为空")]
        public string Name { get; set; }
        [Range(18, 120, ErrorMessage = "年龄不合理")]
        public int age { get; set; }
        [EmailAddress(ErrorMessage = "请填写正确的Email地址")]
        public string Email { get; set; }

    }
}

2、

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using TempTest.Models;

namespace TempTest.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class VerifController : ControllerBase
    {
        [HttpPost]
        public DateTime GetDates([FromBody]UserModel model) //api自定义类型,指定时间类型吧
        {
            return DateTime.Now;
        }
    }
}

中间配置

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            //模型绑定 特性验证,自定义返回格式
            services.Configure<ApiBehaviorOptions>(options =>
            {
                options.InvalidModelStateResponseFactory = actionContext =>
                {
                    //获取验证失败的模型字段 
                    var errors = actionContext.ModelState
                    .Where(e => e.Value.Errors.Count > 0)
                    .Select(e => e.Value.Errors.First().ErrorMessage)
                    .ToList();
                    var str = string.Join("|", errors);
                    //设置返回内容
                    var result = new
                    {
                        code = 12001,
                        body = false,
                        msg = str
                    };
                    return new BadRequestObjectResult(result);
                };
            });
        }

ajax的示例

 

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<body>
</body>
    <script type="text/javascript">
    $(function(){
        $.ajax({
             url:"http://localhost:51117/api/Verif/GetDates",
             type:"post",
             data:{Name:""},
             async:true,

             dataType: "json",
             success:function (data) {
                 console.log(data);
             },
             error:function (data) {
                 console.log(data.status);
             }
         })
    })
    </script>
</html>

也是因为Startup.cs起始代码庞大,故封装注入即可。

其他使用方式: