ビューモデルで10進数を受け取るasp.net mvc Web APIを使用するWeb APIアプリケーションがあります。typeのカスタム モデル バインダーを作成し、decimal
すべての 10 進数で機能させたいと考えています。次のようなビューモデルがあります。
public class ViewModel
{
public decimal Factor { get; set; }
// other properties
}
また、フロントエンド アプリケーションは、次のような無効な 10 進数を含む 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());
私に何ができる?ありがとうございました。