问题
How do I handle NullReferenceException for the below statement as I get null exception error for the below statement 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. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
回答1:
You are getting this exception because RouteDate.Values["Language"] is null and you are applying instance method .ToString on it.
just add an if to check for null
string lang="";
if(RouteData.Values["Language"] != null)
lang = RouteData.Values["Language"].ToString();
回答2:
Newer versions of .NET support:
string lang = (RouteData.Values["Language"] ?? String.Empty).ToString();
Also handy for other data types:
int langId = Convert.ToInt32(RouteData.Values["LanguageId"] ?? 0);
回答3:
try this:
string lang = RouteData.Values["Language"] != null
? RouteData.Values["Language"].ToString()
: String.Empty;
来源:https://stackoverflow.com/questions/10533437/routedata-values-return-nullreferenceexception-when-querystring-is-not-present