简体   繁体   中英

ASP Core WebApi: Single setup to format all query parameters snake_case

Let's assume I have this simple controller action

[HttpGet]
public IEnumerable<WeatherForecast> Get([FromQuery] Query query)
{
    // Return filtered weather forecasts...
}

...and this Query model:

public class Query
{
    public string City { get; set; }
    public int TotalDays { get; set; } = 7;
}

Now, the request path looks like: /weatherforecast?City=Berlin&TotalDays=3

How can I introduce a general configuration to format all PascalCase model properties / camelCase action parameters written in C# into snake_case query parameters requesting by the consumer :
/weatherforecast?city=Berlin&total_days=3


By the way,

I would suggest you to create a middleware to achieve in single place

 public class SnakeCaseQueryStringMiddleware
    {
        private readonly RequestDelegate _next;

        public SnakeCaseQueryStringMiddleware(RequestDelegate next)
        {
            _next = next;

        }

        public async Task Invoke(HttpContext httpContext)
        {
            if (httpContext.Request.Query.Any(q => q.Key.Contains("_")))
            {
                var queryitems = httpContext.Request.Query.SelectMany(x => x.Value, (col, value) => new KeyValuePair<string, string>(col.Key, value)).ToList();
            
                List<KeyValuePair<string, string>> queryparameters = new List<KeyValuePair<string, string>>();
                foreach (var item in queryitems)
                {
                    var key = SnakeToPascalCase(item.Key);
                    KeyValuePair<string, string> newqueryparameter = new KeyValuePair<string, string>(key, item.Value);
                    queryparameters.Add(newqueryparameter);
                }

                var qb1 = new QueryBuilder(queryparameters);
                httpContext.Request.QueryString = qb1.ToQueryString();
            }

            await _next(httpContext);
        }

               string SnakeToPascalCase(string input) => System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(input.Replace("_", " ")).Replace(" ", "");

    }

Then you need to register it in Startup.cs

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
     //Support Snake Case QueryString
            app.UseMiddleware<SnakeCaseQueryStringMiddleware>();
    }

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