在ASP.NET Core中,使用Json.NET(现在称为Newtonsoft.Json)进行数据验证时,可以通过以下方法处理数据验证:
public class UserData
{
[Required(ErrorMessage = "用户名不能为空")]
[StringLength(50, ErrorMessage = "用户名长度不能超过50个字符")]
public string Username { get; set; }
[Required(ErrorMessage = "密码不能为空")]
[StringLength(100, ErrorMessage = "密码长度不能超过100个字符")]
public string Password { get; set; }
[Required(ErrorMessage = "电子邮件不能为空")]
[EmailAddress(ErrorMessage = "电子邮件格式不正确")]
public string Email { get; set; }
}
ActionResult
。例如:using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
[HttpPost]
public async Task<IActionResult> Create([FromBody] UserData userData)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// 保存用户数据并返回成功响应
// ...
return CreatedAtAction(nameof(Get), new { id = userData.Username }, userData);
}
}
IExceptionHandler
接口并在GlobalExceptionHandler
类中注册它。例如:using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Routing;
public class CustomExceptionHandler : IExceptionHandler
{
public Task HandleAsync(ExceptionContext context)
{
if (context.ExceptionHandled || !context.HttpContext.Request.IsAjaxRequest())
{
return Task.CompletedTask;
}
context.Result = new HttpStatusCodeResult(HttpStatusCode.BadRequest);
context.ExceptionHandled = true;
return Task.CompletedTask;
}
}
public class GlobalExceptionHandler : IExceptionFilter
{
private readonly CustomExceptionHandler _exceptionHandler;
public GlobalExceptionHandler(CustomExceptionHandler exceptionHandler)
{
_exceptionHandler = exceptionHandler;
}
public void OnException(ExceptionContext context)
{
_exceptionHandler.HandleAsync(context).Wait();
}
}
然后,在Startup.cs
中注册自定义错误处理程序:
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddControllersWithViews()
.AddRazorPages()
.AddViewOptions(options =>
{
options.HtmlHelperOptions.ErrorContext = new ErrorContext
{
ModelState = new ModelStateDictionary()
};
})
.AddGlobalExceptionFilter(new GlobalExceptionHandler(new CustomExceptionHandler()));
}
这样,当数据验证失败时,系统将返回一个包含错误信息的JSON响应。