QueryString.Add不为ASP.NET Core中的请求查询字符串增加值

Zee*_*dil 1 .net c# .net-core asp.net-core asp.net-core-webapi

我正在编写一个中间件,我想在其中修改当前请求的查询字符串值,但是我无法做到这一点。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());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我将非常感谢对此的任何帮助。

can*_*on7 5

QueryString.Add返回一个QueryString包含给定名称和值的新值。它不会改变QueryString调用它的对象。

所以你需要做类似的事情

request.QueryString = request.QueryString.Add("A", "B");
Run Code Online (Sandbox Code Playgroud)