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

2019-08-24 09:32发布

问题:

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

回答1:

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
}


回答2:

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