RouteData.Values ​​Returns NullReferenceException if no request

How do I handle a NullReferenceException for the statement below, since I get a null exception error for the statement below if it is not present in the query string when using URL routing

string lang = RouteData.Values["Language"].ToString();

Error Details

Description: An unhandled exception occurred during the execution of the current web request. Check the stack trace for more information about the error and where it appeared in the code.

Exception Details: System.NullReferenceException: The object reference was not set to the object instance.

+3
source share
3 answers

, RouteDate.Values ​​[ "" ] , .ToString .
if, null

string lang="";
if(RouteData.Values["Language"] != null)
      lang = RouteData.Values["Language"].ToString();
+4

.NET:

string lang = (RouteData.Values["Language"] ?? String.Empty).ToString();

:

int langId = Convert.ToInt32(RouteData.Values["LanguageId"] ?? 0);
+3

try the following:

string lang = RouteData.Values["Language"] != null
                   ? RouteData.Values["Language"].ToString()
                   : String.Empty;
+1
source

All Articles