RouteData.值[“语言”].ToString()生成null异常
本文关键字:生成 null 异常 ToString 语言 RouteData | 更新日期: 2024-10-23 12:01:18
我在多语言项目中实现了URL路由,我的链接看起来像这个
1> 使用URL路由http://www.example.com/Default.aspx?page=1&语言=en-US2> 使用URL路由http://www.example.com/1/en-US
3> 第三种情况可能是http://www.example.com/Default.aspx或http://www.example.com
我可以检查查询字符串是否为null或RouteData值是否为null
但在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
,则会生成以下错误
我如何让这个语句处理带有out try-catch块的null异常
HttpContext.Current.Request.RequestContext.RouteData.Values["Language"].ToString();
您可以使用RouteValueDictionary.ContainsKey
而不是string.IsNullOrEmpty()
。
目前发生的情况是,您的string.IsNullOrEmpty()
需要一个字符串,因此,您自然会在RouteData上调用.ToString()
。但是,您在一个null对象上调用.ToString()
,这导致了您的错误。我会这样重写:
if (HttpContext.Current.Request.RequestContext.RouteData.Values.ContainsKey("Language")) {
// .. process it here
}
如果.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();
}