我有一個使用asp.net mvc web api的web api應用程序,它在viewmodels中接收一些十進制數。我想爲decimal
類型創建一個自定義模型聯編程序,並讓它適用於所有小數數字。我有一個視圖模型是這樣的:自定義模型綁定器在Asp.Net Web API中的十進制
public class ViewModel
{
public decimal Factor { get; set; }
// other properties
}
而前端應用程序可以發送一個JSON與像一個無效的十進制數:457945789654987654897654987.79746579651326549876541326879854
我想響應與400 - Bad Request
錯誤和自定義信息。我嘗試創建一個自定義模型綁定器,實現global.asax上的System.Web.Http.ModelBinding.IModelBinder
和registring,但不起作用。我想獲得它的工作在我的代碼的所有小數,看看我的嘗試:
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());
我能做些什麼? 謝謝。
你有沒有試圖指定的操作參數類型前的粘合劑在操作的參數之前將這個? [ModelBinder(typeof(DecimalValidatorModelBinder))] – Fals
這將驗證我的小數屬性或我的整個對象上post方法嗎?我只是想驗證我的小數屬性在所有帖子中 –
也許這可以解決您的問題http:// stackoverflow。 com/questions/9434848/custom-model-binder-to-bind-nested-property-values – Fals