c# - 处理 ASP.NET Core Web API 对象属性绑定
问题描述
我有一个 ASP.NET Core 2.1 Web API 应用程序。如果我将空引号作为请求正文中的 json 对象属性值发送到 API 端点,我将使用 null 初始化该属性(它是 Guid 类型?)。我怎样才能改变这种行为?我需要的只是发送 BadRequest (400) 作为响应错误代码。
那是一个端点:
public async Task<ActionResult<ExampleResponse>> ExamplePatch([FromBody] ExampleModel exampleModel,
CancellationToken cancellationToken)
{
/* At this point exampleModel.ExampleGuid is initilized with null. So it should be handled before */
/* some processing */
return StatusCode(StatusCodes.Status201Created, ExampleResponse);
}
这是模型:
[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "9.10.53.0 (Newtonsoft.Json v9.0.0.0)")]
public class ExampleModel
{
/* a bunch of properties here */
[Newtonsoft.Json.JsonProperty("exampleGuid", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public System.Guid? ExampleGuid { get; set; }
}
来自请求正文的 Json:
{ ... other parameters here ..., "exampleGuid": "" }
我对此有一个限制 - 我无法向该模型属性添加属性或以某种方式更改模型。我会非常感谢任何帮助!
解决方案
您可以使用 FluentValidation 包为 ExampleModel 创建一个验证器。这是示例:
public class ExampleModelValidator : AbstractValidator<ExampleModel>
{
public ExampleModelValidator()
{
RuleFor(e => e.ExampleGuid)
.Must(guid => guid.ToString().lenght > 0)
.When(e => e.ExampleGuid.HasValue)
.WithMessage("Must be a valid GUID");
}
}
这将在端点正文之前验证您的模型。
另外,我个人喜欢在我的 Startup.cs 中添加这段代码:
public void ConfigureServices(IServiceCollection services)
{
services
.AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<ExampleModelValidator>())
.ConfigureApiBehaviorOptions(options =>
{
options.InvalidModelStateResponseFactory = context =>
{
var errorsList = string.Join(" | ", context.ModelState.Values.SelectMany(v => v.Errors).Select(err => err.ErrorMessage).ToArray());
return new BadRequestObjectResult(errorsList);
};
});
}
这将返回由管道和 BadRequest 分隔的所有验证消息作为响应。
推荐阅读
- android - Android spinner 后台问题 API 21
- c# - 未使用 WPF DataTemplateSelector
- json - JSONDecodeError:期望值。从 s 解码 JSON 文档(以 JSON 文档开头的 str)
- python - 从 django 查询中获取消息
- javascript - 将组件转换为自定义 Angular 表单控件?
- markdown - 自定义降价增强预览
- r-exams - R/exams 似乎没有返回正确的考试解决方案
- google-chrome - SERVICE WORKER:Service Worker 导航预加载请求因网络错误而失败:Chrome 89 中的 net::ERR_INTERNET_DISCONNECTED
- r - 根据其他三个列中的条件创建新列
- python - 将 html 代码从 python 放入 html 文件