(一)创建项目
一、新建webapi项目
1.打开VS2019,新建项目,选择ASP.NET Web 应用程序(.NET Framework),框架选择.NET Framework4.5,如下图所示。
2.选择空项目,勾选Web API选项,去掉https支持,如下图所示
3.一般在前后端分离的项目中,后端返回的事json格式的数据,但是我们浏览器中显示的是xml格式的,这里需要修改“WebApiConfig”,添加以下代码,让它默认显示JSON的数据
var formatters = config.Formatters.Where(formatter =>
formatter.SupportedMediaTypes.Where(media =>
media.MediaType.ToString() == "application/xml" || media.MediaType.ToString() == "text/html").Count() > 0) //找到请求头信息中的介质类型
.ToList();
foreach (var match in formatters)
{
config.Formatters.Remove(match); //移除请求头信息中的XML格式
}
复制代码
4.Model文件夹下新建一个Person实体类
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Sex { get; set; }
public int Age { get; set; }
}
复制代码
5.在我们的控制器里写一个Get请求方法,
Person[] person = new Person[]
{
new Person { Id = 1, Name = "张三", Sex = "男", Age = 18 },
new Person { Id = 1, Name = "李四", Sex = "女", Age = 18 },
new Person { Id = 1, Name = "王二", Sex = "男", Age = 22 },
new Person { Id = 1, Name = "麻子", Sex = "男", Age = 23 },
};
[HttpGet]
public IHttpActionResult index()
{
return Ok(person);
}
复制代码
二.参数检查验证
1.Nuget安装FluentValidation.WebApi
2.修改Pserson类
[Validator(typeof(PersonValidator))]
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Sex { get; set; }
public int Age { get; set; }
}
public class PersonValidator : AbstractValidator<Person>
{
public PersonValidator()
{
RuleFor(m => m.Id).NotEmpty().NotNull().WithMessage("Id不能为空");
RuleFor(m => m.Name).NotEmpty().NotNull().WithMessage("Name不能为空");
}
}
复制代码
3.让 FluentValidation 生效,在 WebApiConfig中添加如下配置
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
...
FluentValidationModelValidatorProvider.Configure(config);
}
}
复制代码
复制代码
4.新建Filter文件夹并添加ParamsFilterAttribute类
public class ParamsFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
//如果参数非法
if ( !actionContext.ModelState.IsValid)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
}
//如果没有输入参数
else if (actionContext.ActionArguments.Values.First() == null)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest,"请输入参数!");
}
}
}
复制代码
5.控制器新建一个post请求
[HttpPost]
[ParamsFilter]
[Route("params")]
public IHttpActionResult Params([FromBody] Person person)
{
return Json(person);
}
复制代码
postman模拟post请求,在body什么都不输入,提示请输入参数:
输入id,不输入name,提示name不能为空:
输入正确的参数,返回了数据:
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END