C#で操作されたQueryStringを出力する
-
04-07-2019 - |
質問
次のコードを使用すると、適切なフォーマットの文字列が得られます。
Request.QueryString.ToString
& hello = world& microsoft = sucksのようなものをくれます
ただし、このコードを使用してコレクションを別のオブジェクト(同じ型)に複製すると、代わりにToString()メソッドからType()が返されます。
System.Collections.Specialized.NameValueCollection variables = new System.Collections.Specialized.NameValueCollection(Request.QueryString);
if (!string.IsNullOrEmpty(variables["sid"]))
variables.Remove("sid");
Response.Write(variables.ToString());
文字列を手作業で探して構築するのではなく、出力を整理する方法はありますか?
解決
Reflectorを使用して HttpValueCollection
クラスを独自のクラスに抽出し、それを使用することもできます。
他のヒント
HttpValueCollectionは内部ですが、" var"を使用できます。リフレクターで抽出せずに宣言する。
var query = HttpUtility.ParseQueryString(Request.Url.Query);
query["Lang"] = myLanguage; // Add or replace param
string myNewUrl = Request.Url.AbsolutePath + "?" + query;
実際には、HTTPValueCollection型の特別なNVCであるため。 したがって、その上で.ToStringを呼び出すと、正しくフォーマットする方法がわかります。
QueryStringコレクションを新しいNameValueCollectionにコピーする理由
if (!string.IsNullOrEmpty(Request.QueryString["sid"]))
Request.QueryString.Remove("sid");
はい、確かに、間違っています。読み取り専用です。本質は、NameValuecollectionでRemoveメソッドを使用することです:
System.Collections.Specialized.NameValueCollection variables = new System.Collections.Specialized.NameValueCollection(Request.QueryString);
if (!string.IsNullOrEmpty(variables["sid"]))
variables.Remove("sid");
NameValueCollectionが絶対に必要でない場合、辞書には多くの同じセマンティクスがあります:
var variables = Request.QueryString.OfType<DictionaryEntry>()
.Where(entry => entry.Key != "sid")
.ToDictionary(entry => entry.Key, entry => entry.Value);
Request.QueryStringは、実際にはHttpValueCollectionオブジェクトを返します(残念ながら、これはSystem.Webの内部にあるため、できません)。
それでも、HttpValueCollectionはNameValueCollectionから派生し、Remove()メソッドはそのままなので、Request.QueryString.Remove(&quot; sid&quot;);を呼び出すことができるはずです