我有一个自定义模型绑定器,用于REST API,如下所示:
public class CustomQueryModelBinder : IModelBinder { public Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext) { if (!String.IsNullOrWhiteSpace(bindingContext.ModelName) && bindingContext.ModelType == typeof(short) && bindingContext.ValueProvider.GetValue(bindingContext.ModelName) != null) { short value; var val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).FirstValue as string; if (String.IsNullOrWhiteSpace(val)) { return ModelBindingResult.SuccessAsync(bindingContext.ModelName,val); } else if (Int16.TryParse(val,out value) && value >= 0) { return ModelBindingResult.SuccessAsync(bindingContext.ModelName,value); } else { bindingContext.ModelState.AddModelError(bindingContext.ModelName,"The value is invalid."); } } return ModelBindingResult.FailedAsync(bindingContext.ModelName); } }
并且在URI中未指定自定义值的情况下,它应默认为有效值(大于0),但它始终默认为0,即使控制器如下所示:
public async Task<IActionResult> GetAsync( [ModelBinder(BinderType = typeof(CustomQueryModelBinder))]short value = 100,
当从ModelBinder返回null时,这里的基本值应设置为100作为其默认值.
但是这没有发生,并且它一直被返回为0,这在尝试执行Get时导致System.ArgumentOutOfRangeException.
我们正在使用RC1.
解决方法
用短的替换短值= 100?值= 100似乎对我有用. Hooray适用于可空类型.