0

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();
Cœur
  • 37,241
  • 25
  • 195
  • 267
Learning
  • 19,469
  • 39
  • 180
  • 373

2 Answers2

3

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
}
Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138
  • I also got good answer with explanation of link http://stackoverflow.com/questions/10533437/routedata-values-return-nullreferenceexception-when-querystring-is-not-present – Learning Aug 06 '12 at 04:49
0

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();
}
Eren Ersönmez
  • 38,383
  • 7
  • 71
  • 92