asp.net core 2.2:如何使用json转换器触发类型验证?

时间:2019-06-18 20:42:39

标签: c# asp.net-core asp.net-core-2.2

我有几种这样的类型:

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    [HttpPost]
    public IActionResult Post([FromBody] ComplexType value)
    {
        return Ok(value.Value.Value);
    }

}

public class ComplexType
{
    public BindingTestType Value { get; set; }
}

[JsonConverter(typeof(MyConverter))]
[ModelBinder(BinderType=typeof(MyBinder))]
public class BindingTestType
{
    public string Value { get; set; }
}

public class MyBinder:IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        bindingContext.ModelState.TryAddModelError(bindingContext.ModelName, "From Binder");
        return Task.CompletedTask;
    }
}

public class MyConverter:JsonConverter<BindingTestType>
{
    public override void WriteJson(JsonWriter writer, BindingTestType value, JsonSerializer serializer)
    {
        serializer.Serialize(writer,value.Value);
    }

    public override BindingTestType ReadJson(JsonReader reader, Type objectType, BindingTestType existingValue, bool hasExistingValue,
        JsonSerializer serializer)
    {
        return new BindingTestType{Value = "From Converter"};
    }
}

如何更改它们以执行模型绑定验证而不是使用JSON转换器?

0 个答案:

没有答案