使Web API IModelBinder应用于该类型的所有实例

本文关键字:实例 类型 Web API IModelBinder 应用于 | 更新日期: 2023-09-27 18:25:13

我正在使用自定义IModelBinder尝试将字符串转换为NodaTime LocalDates。我的LocalDateBinder看起来像这样:

public class LocalDateBinder : IModelBinder
{
    private readonly LocalDatePattern _localDatePattern = LocalDatePattern.IsoPattern;
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType != typeof(LocalDate))
            return false;
        var val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (val == null)
            return false;
        var rawValue = val.RawValue as string;
        var result = _localDatePattern.Parse(rawValue);
        if (result.Success)
            bindingContext.Model = result.Value;
        return result.Success;
    }
}

在我的WebApiConfig中,我使用SimpleModelBinderProvider注册了这个模型绑定器,这是一个

var provider = new SimpleModelBinderProvider(typeof(LocalDate), new LocalDateBinder());
config.Services.Insert(typeof(ModelBinderProvider), 0, provider);

当我有一个采用LocalDate类型参数的操作时,这非常有效,但如果我有一一个在另一个模型中使用LocalDate的更复杂的操作,它永远不会被激发。例如:

[HttpGet]
[Route("validateDates")]
public async Task<IHttpActionResult> ValidateDates(string userName, [FromUri] LocalDate beginDate, [FromUri] LocalDate endDate)
{
     //works fine
}
[HttpPost]
[Route("")]
public async Task<IHttpActionResult> Create(CreateRequest createRequest)
{
     //doesn't bind LocalDate properties inside createRequest (other properties are bound correctly)
     //i.e., createRequest.StartDate isn't bound
}

我想这与我如何使用Web API注册模型活页夹有关,但我不知道我需要纠正什么——我需要自定义活页夹提供商吗?

使Web API IModelBinder应用于该类型的所有实例

您的CreateRequest是一个复杂类型,它没有定义模型绑定器的类型转换器。在这种情况下,WebApi将尝试使用媒体类型格式化程序。当您使用JSON时,它将尝试使用默认的JSON格式化程序,即标准配置中的NewtonsoftJson.Net。Json.Net不知道如何开箱即用地处理Noda Time类型。

为了使Json.Net能够处理NodaTime类型,您应该安装NodaTime.Serialization.JsonNet,并在启动代码中添加类似的内容。。。

public void Config(IAppBuilder app)
{
    var config = new HttpConfiguration();
    config.Formatters.JsonFormatter.SerializerSettings.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
    app.UseWebApi(config);
}

之后,第二个示例将按预期工作,如果输入的格式不是Noda Time,则ModelState.IsValid将为false

请参阅http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api获取有关Web API中参数绑定的更多信息。