简体   繁体   中英

URI QueryString JsonSerializerSettings and Asp.Net Core

In .Net Core 1.1

Below snippet is working fine for input/output(Body) format

//ConfigureServices

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

I am expecting for query string also same behaviour

Example :

/url/GetData?system_name=intel&is_active=true

Api

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

Any suggestion how can I query string model bind with Camelcase back. Thanks in Advance

Also please let me know if you need any further info

:)

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);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM