2

im getting null exception . while im directly exceciting this page. i want to handle null exception

C#

string json = "";
if (Request.QueryString["data"] !="")
{
    json = Request.QueryString["data"];

    var req = JsonConvert.DeserializeObject<Request>(json);//getting error in this line
    string requestid = req.requestId;
    SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MYSTRING"].ConnectionString);
    SqlCommand cmd = new SqlCommand();
    connection.Open();
}

error

Value cannot be null. Parameter name: value

1
  • You should handle DeserializeObject's exception as well in case the parameter is not json format Commented Sep 24, 2015 at 6:58

4 Answers 4

5

Well presumably Request.QueryString["data"] is null. You're currently checking whether it's a reference to an empty string, but not whether it's a null reference. I suspect you want to use string.IsNullOrEmpty to check that:

string json = Request.QueryString["data"];
if (!string.IsNullOrEmpty(json))
{
     var req = JsonConvert.DeserializeObject<Request>(json);
     ...
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can follow following two approach:-

Approach 1:

if (Request.QueryString["data"] != null && Request.QueryString["data"].toString() != string.Empty)
{
   .. Your Content Goes Here
}

Approach 2:

if (!string.IsNullOrEmpty(Request.QueryString["data"].toString()))
{
   .. Your Content Goes Here
}

Comments

0

you can u string.isNullOrwhiteSpace() Method and it returns a bool ...true if the input is empty ...false if there is any characters

Comments

0

You are getting such error when Request.QueryString["data"] is null. so you should check for null before using this value. in c# null cannot directly converted to String. Better method is suggested by john skeet.

 string json=Request.QueryString["data"];
 if(string.IsNullOrEmpty(json)){//Do your code;}

2 Comments

giving error - Object reference not set to an instance of an object.
Request.QueryString["data"] can be null

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.