RouteData.Values查询字符串时,返回的NullReferenceException不存在 [英] RouteData.Values Return NullReferenceException when querystring is not present
问题描述
如何处理NullReferenceException为下面的语句,因为我得到null异常错误下面的语句,如果它在查询字符串中不存在使用URL路由
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();
错误详情
在当前Web请求的执行期间发生异常。
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.
异常详细信息:System.NullReferenceException:未将对象引用设置为实例的对象。
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
推荐答案
你得到这个异常,因为RouteDate.Values [Language]为null, ToString就可以了。
只是添加一个if来检查null
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();
这篇关于RouteData.Values查询字符串时,返回的NullReferenceException不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!