Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RouteData.Values Return NullReferenceException when querystring is not present

Tags:

c#

routes

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.

like image 715
Learning Avatar asked Aug 31 '26 17:08

Learning


1 Answers

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();
like image 91
Habib Avatar answered Sep 02 '26 05:09

Habib