using System;
using System.ComponentModel;
using System.Globalization;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Mvc.ModelBinding
{
///
/// An for binding , ,
/// , and their wrappers.
/// Modified to set and .
///
///
/// To use this provider, insert it at the beginning of the providers list:
///
/// services.AddControllersWithViews(options =>
/// {
/// options.ModelBinderProviders.Insert(0, new CustomFloatingPointModelBinderProvider());
/// });
///
public class InvariantFloatingPointModelBinderProvider : IModelBinderProvider
{
///
/// Gets or sets the supported globally.
/// Default: and .
///
///
/// uses and similar. Those s default to .
///
public static NumberStyles SupportedNumberStyles { get; set; } = NumberStyles.Float | NumberStyles.AllowThousands;
///
/// Gets or sets the to use while parsing globally.
/// Default: .
///
public static CultureInfo CultureInfo { get; set; } = CultureInfo.InvariantCulture;
///
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
var loggerFactory = context.Services.GetRequiredService();
var modelType = context.Metadata.UnderlyingOrModelType;
if (modelType == typeof(decimal) ||
modelType == typeof(double) ||
modelType == typeof(float))
{
return new InvariantFloatingPointModelBinder(SupportedNumberStyles, CultureInfo, loggerFactory);
}
return null;
}
}
}