【问题标题】:RouteData.Values["Language"].ToString() generate null exceptionRouteData.Values["Language"].ToString() 生成空异常
【发布时间】:2012-08-03 02:08:29
【问题描述】:

我在我的多语言项目中实现了 URL 路由,我的链接看起来像这样

1> 带有 URL 路由 http://www.example.com/Default.aspx?page=1&Language=en-US 2> 带URL路由http://www.example.com/1/en-US

3> 第三种情况可以是http://www.example.com/Default.aspxhttp://www.example.com

我可以检查查询字符串是否为空或 RouteData 值是否为空

但在 3 种情况下,我必须检测浏览器默认语言并根据它们重定向。

如果我把我的代码写成

if (!string.IsNullOrEmpty(Request["Language"]))
  {
   lang = Request["Language"].ToString();
  }
if (!string.IsNullOrEmpty(HttpContext.Current.Request.RequestContext.RouteData.Values["Language"].ToString()))
 {
    lang = HttpContext.Current.Request.RequestContext.RouteData.Values["Language"].ToString();
 }

如果路由数据为空Object reference not set to an instance of an object会产生以下错误

如何让这个语句在没有 try catch 块的情况下处理空异常

HttpContext.Current.Request.RequestContext.RouteData.Values["Language"].ToString();

【问题讨论】:

    标签: c# asp.net url-routing


    【解决方案1】:

    您可以使用RouteValueDictionary.ContainsKey 代替string.IsNullOrEmpty()

    目前发生的情况是,您的 string.IsNullOrEmpty() 需要一个字符串,因此,您自然会在 RouteData 上调用 .ToString()。但是,您在 null 对象上调用 .ToString(),这会导致您的错误。我会这样重写它:

    if (HttpContext.Current.Request.RequestContext.RouteData.Values.ContainsKey("Language")) {
        // .. process it here
    }
    

    【讨论】:

    【解决方案2】:

    如果.Values["Language"] 产生null,您可以像这样检查它:

    if(HttpContext.Current.Request.RequestContext.RouteData != null)
    {
        var value = HttpContext.Current.Request.RequestContext.RouteData.Values["Language"];
        lang = value == null ? null : value.ToString();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-24
      • 1970-01-01
      • 2014-08-29
      • 1970-01-01
      • 2016-10-07
      • 2013-04-08
      • 1970-01-01
      相关资源
      最近更新 更多