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

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

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

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

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

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


慕田峪4524236
浏览 44回答 1
1回答

慕尼黑5688855

要删除查询字符串,您可以尝试Middleware像app.Use(async (context,next) =>{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; if (context.Request.Query.TryGetValue("fbclid", out StringValues query))&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var items = context.Request.Query.SelectMany(x => x.Value, (col, value) => new KeyValuePair<string, string>(col.Key, value)).ToList();&nbsp; &nbsp; &nbsp; &nbsp; // At this point you can remove items if you want&nbsp; &nbsp; &nbsp; &nbsp; items.RemoveAll(x => x.Key == "fbclid"); // Remove all values for key&nbsp; &nbsp; &nbsp; &nbsp; var qb = new QueryBuilder(items);&nbsp; &nbsp; &nbsp; &nbsp; context.Request.QueryString = qb.ToQueryString();&nbsp; &nbsp; }&nbsp; &nbsp; await next.Invoke();});
打开App,查看更多内容
随时随地看视频慕课网APP