RouteData.Values[“Language"].ToString() 生成空异常 [英] RouteData.Values["Language"].ToString() generate null exception

查看:30
本文介绍了RouteData.Values[“Language"].ToString() 生成空异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I implemented URL routing in my multilingual project my link looks like this

1> 使用 URL 路由 http://www.example.com/Default.aspx?page=1&Language=en-US2> 使用 URL 路由 http://www.example.com/1/en-US

1> with URL Routing http://www.example.com/Default.aspx?page=1&Language=en-US 2> With URL Routing http://www.example.com/1/en-US

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

3> and 3rd scenario can be http://www.example.com/Default.aspx or http://www.example.com

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

I can check if query string is null or RouteData value is null

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

but in 3 case i have to detect the browser default language & redirect them according.

如果我把代码写成

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();
 }

如果路由数据为空,它会产生以下错误未将对象引用设置为对象的实例

It generate following error if Route Data is null Object reference not set to an instance of an object

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

How can i make this statement handle null exception with out try catch block

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

推荐答案

您可以使用 RouteValueDictionary.ContainsKey 而不是 string.IsNullOrEmpty().

You can use RouteValueDictionary.ContainsKey instead of string.IsNullOrEmpty().

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

What's happening at the moment, is your string.IsNullOrEmpty() requires a string, so, naturally you're calling .ToString() on the RouteData. However, you're calling .ToString() on a null object, which is causing your error. I would re-write it like this:

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

这篇关于RouteData.Values[“Language"].ToString() 生成空异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆