Parse and modify a query string in .NET Core

后端 未结 6 631
無奈伤痛
無奈伤痛 2020-11-29 00:38

I am given an absolute URI that contains a query string. I\'m looking to safely append a value to the query string, and change an existing parameter.

I would prefer

6条回答
  •  时光取名叫无心
    2020-11-29 01:20

    If you are using ASP.NET Core 1 or 2, you can do this with Microsoft.AspNetCore.WebUtilities.QueryHelpers in the Microsoft.AspNetCore.WebUtilities package.

    If you are using ASP.NET Core 3.0 or greater, WebUtilities is now part of the ASP.NET SDK and does not require a separate nuget package reference.

    To parse it into a dictionary:

    var uri = new Uri(context.RedirectUri);
    var queryDictionary = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(uri.Query);
    

    Note that unlike ParseQueryString in System.Web, this returns a dictionary of type IDictionary in ASP.NET Core 1.x, or IDictionary in ASP.NET Core 2.x or greater, so the value is a collection of strings. This is how the dictionary handles multiple query string parameters with the same name.

    If you want to add a parameter on to the query string, you can use another method on QueryHelpers:

    var parametersToAdd = new System.Collections.Generic.Dictionary { { "resource", "foo" } };
    var someUrl = "http://www.google.com";
    var newUri = Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString(someUrl, parametersToAdd);
    

    Using .net core 2.2 you can get the query string using

    var request = HttpContext.Request;
    var query = request.query;
    foreach (var item in query){
       Debug.WriteLine(item) 
    }
    

    You will get a collection of key:value pairs - like this

    [0] {[companyName, ]}
    [1] {[shop, ]}
    [2] {[breath, ]}
    [3] {[hand, ]}
    [4] {[eye, ]}
    [5] {[firstAid, ]}
    [6] {[eyeCleaner, ]}
    

提交回复
热议问题