RouteData.Values[“Language”].ToString() generate n

2019-08-24 10:08发布

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

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> and 3rd scenario can be http://www.example.com/Default.aspx or http://www.example.com

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

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

if i write my code as

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

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

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

2条回答
时光不老,我们不散
2楼-- · 2019-08-24 10:11

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

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
}
查看更多
放我归山
3楼-- · 2019-08-24 10:30

If .Values["Language"] is producing null, you can check against it like this:

if(HttpContext.Current.Request.RequestContext.RouteData != null)
{
    var value = HttpContext.Current.Request.RequestContext.RouteData.Values["Language"];
    lang = value == null ? null : value.ToString();
}
查看更多
登录 后发表回答