asp.net-core – 当返回null而不是控制器中设置的值时,Modelbind
发布时间:2020-12-16 04:06:48 所属栏目:asp.Net 来源:网络整理
导读:我有一个自定义模型绑定器,用于REST API,如下所示: public class CustomQueryModelBinder : IModelBinder{ public TaskModelBindingResult BindModelAsync(ModelBindingContext bindingContext) { if (!String.IsNullOrWhiteSpace(bindingContext.ModelName
我有一个自定义模型绑定器,用于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适用于可空类型.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net – IIS 8.5提供旧文件
- 在ASP.NET 3.5中实现异常处理
- asp.net – 数据库交互/业务逻辑在MVC中发生在哪里?
- asp.net – System.Diagnostics.Process.Start不能从IIS工作
- asp.net – 如何从.aspx页面检索查询字符串值并将其传递给a
- asp.net – 使用IronPython调用带有参数的Python脚本 – “
- nuget-package – 如何在asp.net 5应用程序中添加项目引用
- asp.net – 在发布Web应用程序时如何包含未引用的dll?
- asp.net-mvc – Visual Studio 2015异步变量未在调试器中显
- ASP.NET Web Api:如何使用URL参数传递访问令牌(oAuth 2.0)
推荐文章
站长推荐
热点阅读