c# - 为什么 StringValues 用于 Request.Query 值?

标签 c# asp.net-core

假设我有一些如下所示的 url:www.myhost.com/mypage?color=blue

在 Asp.Net Core 中,我希望通过执行以下操作来获取颜色查询参数值:

string color = Request.Query["color"];

但事实证明,Request.Query["color"] 返回类型为 StringValues 的值,而不是 string。这是为什么?

显然,StringValues 类型可以保存一个字符串数组,并支持隐式转换为 string[],这很酷,但为什么需要查询参数值?

必须得到这样的值看起来很奇怪:

string color = Request.Query["color"].ToString();

更糟糕的是,检查一个值以查看是否指定了查询参数不能再像这样完成

  if(Request.Query["color"] == null) { 
      //param was not specified
  }

但必须像这样检查

 if(Request.Query["color"].Count == 0) { 
      //param was not specified
 }

由于单个查询参数不能有多个值(据我所知)为什么 Request.Query["color"] 返回一个 StringValues 对象而不是比一个字符串?

最佳答案

正如其他人已经提到的,该类型是一个 StringValues 对象,因为从技术上讲,允许多个值。虽然通常的做法是只设置一个值,但 URI 规范并不禁止多次设置值。由应用决定如何处理。

话虽如此,StringValues 隐式转换为 string,因此您实际上不需要对其调用 ToString() ,你可以像使用字符串一样使用它。因此,执行 Request.Query["color"] == "red" 之类的操作,或将其传递给需要字符串的方法就可以了。

And worse, checking for a value to see if a query param is specified can no longer be done like so Request.Query["color"] == null but instead must be checked like so Request.Query["color"].Count == 0

这只对了一半。是的,为了检查一个 StringValues 对象是否为空,您可以检查它的 Count 属性。您还可以检查 StringValues.Empty:

Request.Query["color"] == StringValues.Empty

但是,最初的“问题”是 Request.Query[x]总是 返回一个非空的 StringValues 对象(所以检查任何值都是安全的)。如果要检查查询参数中是否存在键,应使用 ContainsKey:

if (Request.Query.ContainsKey("color"))
{
    // only now actually retrieve the value
    string colorValue = Request.Query["color"];
}

或者,使用TryGetValue:

if (Request.Query.TryGetValue("color", out var colorValue))
{
    DoSomething(colorValue);
}

总而言之,大多数时候访问 Request.Query 并不是真正必要的。您应该只使用 model binding相反,它会自动为您提供所需的查询参数,只需将它们放在操作的签名中即可:

public ActionResult MyAction(string color)
{
    DoSomething(color);
}

关于c# - 为什么 StringValues 用于 Request.Query 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48188934/

相关文章:

c# - UseInMemoryDatabase 与 UseInternalServiceProvider。没有配置数据库提供程序

c# - ASP.NET-5 测试库不发现主代码

c# - 创建新的数据库并填充另一个数据库

c# - Linq to Entities 奇怪的部署行为

c# - 如何获取通过Azure函数事件中心触发器接收到的事件的messageId或eventId?

c# - 更新到 beta8 后无法发布 asp.net 5 应用程序 - 依赖项......无法解决

c# - 使用前缀、后缀和分隔符连接字符串的最快方法

c# - 软键盘重叠控件(WPF、桌面)

c# - 在.NET core 2 MVC应用程序中配置JWT访问 token

azure - 根据 Azure Functions 2.x 和 VS 的环境自动加载设置文件