C# 在ASP.NET Core中添加而不是向请求查询字符串添加值

C# 在ASP.NET Core中添加而不是向请求查询字符串添加值,c#,.net,asp.net-core,.net-core,asp.net-core-webapi,C#,.net,Asp.net Core,.net Core,Asp.net Core Webapi,我正在编写一个中间件,其中我想修改当前请求的查询字符串值,但我无法这样做。afaikQueryString.Add方法应该可以工作,但不会影响查询字符串。这是我试过的 public async Task Invoke(HttpContext context, IHeaderValue headerValue, IUser user) { var result = context.Request.Headers["Authorization"]; if (result.Count

我正在编写一个中间件,其中我想修改当前请求的查询字符串值,但我无法这样做。afaik
QueryString.Add
方法应该可以工作,但不会影响查询字符串。这是我试过的

public async Task Invoke(HttpContext context, IHeaderValue headerValue, IUser user)
{
    var result = context.Request.Headers["Authorization"];

    if (result.Count != 0)
    {

        headerValue.UserId = this.GetUserIdFromToken(result[0]);

        var request = context.Request;

        if (request.Method == "GET")
        {
            // It should be adding the new query value to the QueryString collection
            // but it doesn't
            request.QueryString.Add("CurrentUserId", headerValue.UserId.ToString());
        }
    }
}
非常感谢您的帮助。

返回一个新的
查询字符串,其中包含给定的名称和值。它不会改变调用它的
查询字符串

所以你需要做一些类似的事情

request.QueryString = request.QueryString.Add("A", "B");

查看
QueryString的返回值。添加
Oh yes!谢谢一吨广东!!!!!我这样做了,它的工作
request.QueryString=request.QueryString.Add(“CurrentUserId”,headerValue.UserId.ToString())请将此作为答案发布,以便更多人获得帮助。