如何在 ASP.NET Core 中间件中重写查询字符串?

问题描述 投票:0回答:2

这是访问我的服务器的 URL:

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

我想将其转换为这个URL,但我不想重定向用户。所以我需要重写:

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

也就是说,我想将

kebab-cased
查询键更改为
camelCased
键。

我怎样才能做到这一点?

这是我尝试过的:

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();
});
c# asp.net-core middleware casing
2个回答
0
投票

Request.QueryString 是只读的,但您可以将其替换为新实例。

您可以使用以下行更改当前请求的查询字符串:

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

示例:

 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
投票

不知道为什么你需要这样做,因为它很hacky。使用

[FromUri]
并将查询字符串映射到原始或复杂类型有什么问题?

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

或者可以映射整个对象 - https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api #using-fromuri

© www.soinside.com 2019 - 2024. All rights reserved.