4

ビューモデルで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.IModelBinderglobal.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());

私に何ができる?ありがとうございました。

4

2 に答える 2

0

JSON の場合、JsonConverter を作成できます (デフォルトで JSON.NET を使用している場合:

public class DoubleConverter : JsonConverter
{
    public override bool CanWrite
    {
        get { return false; }
    }

    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(double) || objectType == typeof(double?));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JToken token = JToken.Load(reader);
        if (token.Type == JTokenType.Float || token.Type == JTokenType.Integer)
        {
            return token.ToObject<double>();
        }
        if (token.Type == JTokenType.String)
        {
            // customize this to suit your needs
            var wantedSeperator = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator;
            var alternateSeparator = wantedSeperator == "," ? "." : ",";
            double actualValue;
            if (double.TryParse(token.ToString().Replace(alternateSeparator, wantedSeperator), NumberStyles.Any,
                CultureInfo.CurrentCulture, out actualValue))
            {
                return actualValue;
            }
            else
            {
                throw new JsonSerializationException("Unexpected token value: " + token.ToString());
            }

        }
        if (token.Type == JTokenType.Null && objectType == typeof(double?))
        {
            return null;
        }
        if (token.Type == JTokenType.Boolean)
        {
            return token.ToObject<bool>() ? 1 : 0;
        }
        throw new JsonSerializationException("Unexpected token type: " + token.Type.ToString());
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException("Unnecessary because CanWrite is false. The type will skip the converter.");
    }
}
于 2015-07-06T09:54:03.537 に答える