RouteData.Values Return NullReferenceException when querystring is not present

点点圈 提交于 2020-01-04 03:11:28

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!