在处理请求之前从请求中删除查询字符串

Use*_*185 4 c# asp.net asp.net-mvc asp.net-mvc-routing asp.net-core

我想删除一个特定的查询字符串(即fbclid),Facebook 将其添加到共享链接中以进行跟踪(我假设)。我需要对所有工作路线执行此操作,但我找不到简单的解决方案。

我正在使用 ASP.NET Core 2.0、AWS lambda、API 网关。

我尝试使用重写器,但当替换为空字符串时,它会引发异常。这是我的代码:

app.UseRewriter(new RewriteOptions()
    .AddRewrite("\\?fbclid=(\\w*)", string.Empty, false));
Run Code Online (Sandbox Code Playgroud)

我不想重定向到干净的 URL 或获取没有查询参数的 URL。相反,我需要更改管道其余部分的当前请求以正确处理它。

Tao*_*hou 5

要删除查询字符串,您可以尝试Middleware

app.Use(async (context,next) =>
{                
    if (context.Request.Query.TryGetValue("fbclid", out StringValues query))
    {
        var items = context.Request.Query.SelectMany(x => x.Value, (col, value) => new KeyValuePair<string, string>(col.Key, value)).ToList();
        // At this point you can remove items if you want
        items.RemoveAll(x => x.Key == "fbclid"); // Remove all values for key
        var qb = new QueryBuilder(items);
        context.Request.QueryString = qb.ToQueryString();
    }
    await next.Invoke();
});
Run Code Online (Sandbox Code Playgroud)