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

时间:2019-09-29 19:23:30

标签: c# asp.net asp.net-mvc asp.net-core asp.net-mvc-routing

我想删除一个特定的查询字符串(即fbclid),Facebook将其添加到共享链接以进行跟踪(我认为),这是我所有上班的路线,但我找不到直接的答案

我正在使用ASP Net Core 2.0,AWS Lambda,API网关

我尝试使用重写器,但是当替换为空字符串时会抛出

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

我不希望重定向到一个干净的URL或获取没有查询参数的URL,而是需要更改当前请求以使其余管道正确处理

1 个答案:

答案 0 :(得分:0)

要删除查询字符串,您可以像

那样尝试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();
});
相关问题