How can I rewrite query string in ASP.NET Core middleware?

493 views Asked by At

This is the URL that comes to my server:

https://example.com/path?key-one=value&key-two=value2

And I want to convert it to this URL, but I don't want to redirect the user. So I need to rewrite:

https://example.com/path?keyOne=value&keyTwo=value2

In other words, I want to change the kebab-cased query keys into camelCased keys.

How can I do that?

This is what I have tried:

app.Use(async (context, next) =>
{
    var collection = context.Request.Query;
    var oldQueryString = context.Request.QueryString;
    var newQueryString = new List<QueryString>();

    foreach (var item in collection)
    {
        var camelizedKey = item.Key.Underscore().Camelize();
        // what should I do here? How do I set the new query, how do I rewrite?
    }

    await next.Invoke();
});
2

There are 2 answers

0
Olaf On

Request.QueryString is readonly, but you can replace it with a new instance.

You can change the querystring of the current request with the following line:

httpContext.Request.QueryString = "yourvalues=here&another=one"

Example:

 if (httpContext.Request.QueryString.HasValue)
    {
        QueryBuilder queryBuilder = new QueryBuilder();
        foreach (var key in httpContext.Request.Query.Keys)
        {
            var realValue = httpContext.Request.Query[key];
            var modifiedValue = HttpUtility.UrlDecode(realValue);
            queryBuilder.Add(key, modifiedValue);
        }
        httpContext.Request.QueryString = queryBuilder.ToQueryString();
    }
    return _next(httpContext);
0
underscoreHao On

Not sure why you need to do this as it's quite hacky. What's wrong with using [FromUri] and mapping your query string to your primitive or complex types?

[HttpGet(Name = "Get")]
public IEnumerable<Foo> GetWithQueryParams([FromUri(Name = "page-number")] int pageNumber)
{ ... }

or can map your entire object - https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api#using-fromuri