ASP 核心中的本地化查询字符串参数

Localized query string parameters in ASP core

我在使用一个控制器时遇到问题,它在查询字符串中获取一对坐标作为参数。

我的控制器看起来像:

[HttpGet("/location")]
public IActionResult GetForLocation(double lat, double lon)
{
// Do stuff
}

当客户端发送带有不同小数点分隔符的坐标(例如 /location?lat=4,4&lon=45,5)时,框架会将它们解析为 44455。我在我的启动 class 中使用了 app.UseRequestLocalization() 并查看了当前的线程文化 我得到了正确的小数点分隔符值,但是模型绑定是错误的。

问这个问题几分钟后我找到了答案,https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-5.0#globalization-behavior-of-model-binding-route-data-and-query-strings

简而言之,查询字符串参数和路径默认被视为不变文化,除非您将 QueryStringValueProviderFactoryRouteValueProviderFactory 替换为以下内容:

    public class CulturedQueryStringValueProviderFactory : IValueProviderFactory
    {
        /// <inheritdoc />
        public Task CreateValueProviderAsync(ValueProviderFactoryContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var query = context.ActionContext.HttpContext.Request.Query;

            if (query != null && query.Count > 0)
            {
                var valueProvider = new QueryStringValueProvider(
                    BindingSource.Query,
                    query,
                    CultureInfo.CurrentCulture);

                context.ValueProviders.Add(valueProvider);
            }

            return Task.CompletedTask;
        }
    }
    public class CulturedRouteValueProviderFactory : IValueProviderFactory
    {
        /// <inheritdoc />
        public Task CreateValueProviderAsync(ValueProviderFactoryContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var valueProvider = new RouteValueProvider(
                BindingSource.Path,
                context.ActionContext.RouteData.Values,
                CultureInfo.CurrentCulture);

            context.ValueProviders.Add(valueProvider);

            return Task.CompletedTask;
        }
    }