【问题标题】:Value cannot be null. Parameter name: String值不能为空。参数名称:字符串
【发布时间】:2012-12-04 11:48:14
【问题描述】:

请看下面的代码。它在handler.asxh

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "application/json";
    new RequestManagementFacade().PinRequest(Int32.Parse(context.Request.QueryString["requestId"]), (Boolean.Parse(context.Request.QueryString["isPinned"])));
}

这显示以下错误:

Value cannot be null. Parameter name: String

当我检查了上下文请求查询字符串时,有值被传递,但是,代码在这个阶段中断了。

这个处理程序将连接到业务逻辑层。

【问题讨论】:

标签: c# exception handler request.querystring nul


【解决方案1】:

有值被传递,因为我检查了上下文请求查询字符串

我强烈怀疑您的诊断结果不正确。价值观不会神奇地消失——你需要质疑你的假设。不过,这很容易调试。我建议将您的代码更改为:

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "application/json";
    string requestId = context.Request.QueryString["requestId"];
    string isPinned = context.Request.QueryString["isPinned"];
    var facade = new RequestManagementFacade();
    facade.PinRequest(Int32.Parse(requestId), Boolean.Parse(isPinned));
}

然后真的很容易通过并找出发生了什么。

【讨论】:

  • 如果你把解析代码也放在不同的行上会更简单: int ID = Int32.Parse(requestId);为了更加稳健,您可以使用 TryParse 并自动处理错误。
  • @SteveWellens:好吧,如果问题是requestIdisPinned 为空,那么在解析调用之前应该清楚。
  • @JonSkeet:这就是我建议 TryParse 的原因......它可以处理空值以及无效的字符串值。
  • @SteveWellens: TryParse 仅在 预计 可能无效时才适用。听起来 OP 真的希望它现在有效,例外是完全合理的回应。不清楚。
【解决方案2】:

很可能context.Request.QueryString["requestId"]context.Request.QueryString["isPinned"] 没有返回有效的字符串值。检查两个值是否都以正确的 ID 在查询字符串中传递,当然是 requestIdisPinned

【讨论】:

  • 好的解决了将值传递给处理程序时我将其插入为“PinRequest.ashx?="+requestId+isPinned" 这给了我结果 2True 所以我意识到打嗝是不包括字符串名称 "PinRequest.ashx?requestId=" + this._requestId + "&isPinned=" + this._isPinned 谢谢你的帮助 LeviBotelho 谢谢你让我检查我在检查它的 javascript 时遗漏的东西。
【解决方案3】:

在将值传递给处理程序时解决了,我将其插入为

"PinRequest.ashx?="+requestId+isPinned"

这给了我 2True 的结果

所以我意识到打嗝是因为不包括字符串名称

"PinRequest.ashx?requestId=" + this._requestId + "&isPinned=" + this._isPinned

谢谢大家的帮助

LeviBotelho 谢谢你让我检查我在检查它的 javascript 时遗漏的东西

【讨论】:

    【解决方案4】:

    在使用 Int32.Parse(myString) 将字符串转换为 int 并随后将值分配给对象的属性时遇到错误。使用另一种方法将 (Convert.ToInt32(myString)) 字符串转换为 int 对我有用。

    【讨论】:

      猜你喜欢
      • 2019-11-06
      • 2018-02-11
      • 2011-12-18
      • 1970-01-01
      • 2013-09-05
      • 1970-01-01
      • 1970-01-01
      • 2021-07-26
      • 1970-01-01
      相关资源
      最近更新 更多