I'm encountering this error whenever I try to execute the code below. As I have checked, the parameters I tried to pass to the controller were null. I really don't know how to fix this. Please help.
Error: System.NullReferenceException was unhandled by user code
Code:
Controller:
public class VisitorController : ApiController
{
static readonly IVisitorRepository repository = new VisitorRepository();
[HttpGet]
public HttpResponseMessage PostVisitor(Visitor guest)
{
guest = repository.AddGuest(guest);
var response = Request.CreateResponse<Visitor(HttpStatusCode.Created, guest);
string uri = Url.Link("DefaultApi", new { id = guest.ID });
response.Headers.Location = new Uri(uri);
return response;
}
}
Model:
public class Visitor
{
public int ID { get; set; }
public string Name { get; set; }
public string Company { get; set; }
public string Contact { get; set; }
public string Email { get; set; }
public string Purpose { get; set; }
public string Location { get; set; }
public DateTime LoggedIn { get; set; }
public DateTime LoggedOut { get; set; }
}
Class:
public Visitor AddGuest(Visitor details)
{
string sp = "AddGuestDetails";
try
{
SqlConnection conn = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(sp, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@ID", SqlDbType.Int).Value = details.ID;
cmd.Parameters.Add("@VisitorName", SqlDbType.NVarChar).Value = details.Name;
cmd.Parameters.Add("@Company", SqlDbType.NVarChar).Value = details.Company;
cmd.Parameters.Add("@Contact", SqlDbType.NVarChar).Value = details.Contact;
cmd.Parameters.Add("@Email", SqlDbType.NVarChar).Value = details.Email;
cmd.Parameters.Add("@Purpose", SqlDbType.NVarChar).Value = details.Purpose;
cmd.Parameters.Add("@Location", SqlDbType.NVarChar).Value = details.Location;
cmd.Parameters.Add("@LogIn", SqlDbType.NVarChar).Value = details.LoggedIn;
cmd.Parameters.Add("@LogOut", SqlDbType.NVarChar).Value = details.LoggedOut;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: '{0}'", ex);
}
return details;
}
execution:
localhost/api/visitor/postvisitor/?>Name=Anna&Company=ABCD&Contact=5555&[email protected]&Purpose=Meeting&Location=Roces&Log>gedIn=07/18/2014%2010:00:00&LoggedOut=07/18/2014%2010:00:00}"