【问题标题】:How to keep url parameters as key-value如何将 url 参数保留为键值
【发布时间】:2020-01-07 19:11:54
【问题描述】:

通常我可以使用httpcontext读取参数inurl,但我想知道url中是否有多个查询参数我可以将它们作为键值获取吗?

网址:localhost:3034/?CustomerID=12345&RoleName=Student

string customerID = this.HttpContext.Request["CustomerID"];
string roleName= this.HttpContext.Request["RoleName"];

我是否有机会将它作为键值保存,而不是像上面那样一一阅读并在项目的任何地方使用它?

提前致谢

【问题讨论】:

  • 您是否希望它作为“键值”,因为您想迭代所有参数?它们目前是键值,因为您输入 CustomerId 的键并取回值。
  • Item[String] 集合是 QueryString、Form、Cookies 和 ServerVariables 集合的组合。我认为 OP 只是在寻找 QueryString 集合,奇怪的是,它似乎不像其他人那样暴露为 NameValueCollection。
  • @AlwaysLearning 实际上是这样。它是 QueryString 属性。
  • @Xipooo ... 这是一个字符串属性,而不是 NameValueCollection。
  • @AlwaysLearning 我向你保证是 :) docs.microsoft.com/en-us/dotnet/api/…

标签: c# httpcontext url-parameters


【解决方案1】:

您可以直接访问 Response 对象的 Headers 属性以获取标头或 QueryString 属性以获取查询参数。他们都已经是一个集合了:

NameValueCollection headers = this.HttpContext.Request.Headers;
NameValueCollection queryParams = this.HttpContext.Request.QueryString;

【讨论】:

  • Request.Headers 集合包含来自传入 HTTP 请求的 HTTP 标头。它不包含 QueryString 值。
  • @AlwaysLearning 好点。他必须将 Headers 用于标头值,将 QueryString 用于查询字符串值等。更新后也包含查询字符串参数。
  • 感谢您的支持@Xipooo 我可以使用“QueryString”达到参数值
猜你喜欢
  • 2015-10-14
  • 1970-01-01
  • 2016-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
相关资源
最近更新 更多