URI QueryString JsonSerializerSettings和Asp.Net Core

时间:2017-03-15 06:22:44

标签: c# asp.net-core

在.Net Core 1.1中

以下代码段适用于输入/输出(正文)格式

// ConfigureServices

.AddJsonOptions(jsonOption =>
 {
   jsonOption.SerializerSettings.ContractResolver = new DefaultContractResolver()
   {
     NamingStrategy = new SnakeCaseNamingStrategy(true, true)
   };
 })

我期待查询字符串也具有相同的行为

示例

/ URL /的GetData系统名称=英特尔&安培; IS_ACTIVE =真

阿比

 public class SystemController : Controller
 {
    public List<string> GetData([FromQuery]string SystemName, FromQuery]bool IsActive)
    { 
      Assert.Equals("intel", SystemName);
      Assert.Equals(true, IsActive);
      return null;
    }
 }

任何建议如何查询字符串模型与Camelcase绑定。 在此先感谢

如果您需要任何进一步的信息,请告诉我

1 个答案:

答案 0 :(得分:0)

:)

using System;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace Application.ValueProviders
{
    public class CamelCaseQueryStringValueProviderFactory : IValueProviderFactory
    {
        public Task CreateValueProviderAsync(ValueProviderFactoryContext context)
        {
            if (context == null)
                throw new ArgumentNullException(nameof(context));
            return AddValueProviderAsync(context);
        }

        private async Task AddValueProviderAsync(ValueProviderFactoryContext context)
        {
            var collection = context.ActionContext.HttpContext.Request.Query
                .ToDictionary(t => ToCamelCaseFromSnakeCase(t.Key), t => t.Value, StringComparer.OrdinalIgnoreCase);

            var valueProvider = new QueryStringValueProvider(
                BindingSource.Query,
                new QueryCollection(collection),
                CultureInfo.InvariantCulture);

            context.ValueProviders.Add(valueProvider);
        }

        private string ToCamelCaseFromSnakeCase(string str)
        {
            return str.Split(new[] { "_" },
                StringSplitOptions.RemoveEmptyEntries).
                Select(s => char.ToUpperInvariant(s[0]) + s.Substring(1, s.Length - 1)).
                Aggregate(string.Empty, (s1, s2) => s1 + s2);
        }
    }
}