gpt4 book ai didi

c# - Asp.Net Web API 中小数的自定义模型绑定(bind)器

转载 作者:太空狗 更新时间:2023-10-30 01:05:39 24 4
gpt4 key购买 nike

我有一个使用 asp.net mvc web api 的 web api 应用程序,它在 View 模型中接收一些十进制数字。我想为 decimal 类型创建一个自定义模型 Binder ,并使其适用于所有小数。我有一个像这样的 View 模型:

public class ViewModel
{
public decimal Factor { get; set; }
// other properties
}

并且前端应用程序可以发送带有无效十进制数的 json,例如:457945789654987654897654987.79746579651326549876541326879854

我想用 400 - Bad Request 错误和自定义消息进行响应。我尝试创建一个自定义模型联编程序实现 System.Web.Http.ModelBinding.IModelBinder 并在 global.asax 上注册字符串但不起作用。我想让它适用于我代码中的所有小数,看看我尝试了什么:

public class DecimalValidatorModelBinder : System.Web.Http.ModelBinding.IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
var input = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

if (input != null && !string.IsNullOrEmpty(input.AttemptedValue))
{
if (bindingContext.ModelType == typeof(decimal))
{
decimal result;
if (!decimal.TryParse(input.AttemptedValue, NumberStyles.Number, Thread.CurrentThread.CurrentCulture, out result))
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, ErrorHelper.GetInternalErrorList("Invalid decimal number"));
return false;
}
}
}

return true; //base.BindModel(controllerContext, bindingContext);
}
}

Application_Start 上添加:

GlobalConfiguration.Configuration.BindParameter(typeof(decimal), new DecimalValidatorModelBinder());

我能做什么?谢谢。

最佳答案

默认情况下,Web API 使用媒体类型格式化程序从请求正文中读取复杂类型。所以在这种情况下它不会通过模型 Binder 。

关于c# - Asp.Net Web API 中小数的自定义模型绑定(bind)器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17955337/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com