'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,
- My
Startup.ConfigureServices(..)usesservices.Configure<RouteOptions>(options => options.LowercaseUrls = true); - I've already read https://medium.com/@xsoheilalizadeh/snake-case-query-string-in-asp-net-core-25fc2d7bdab0
...very cumbersome :-(
Solution 1:[1]
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>();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kuroro |
