I am writing a web api2 program that handles sms-contacts. There is a JSON post to the server like this:
{
"Id":"4",
"ClientId":"2",
"NoOfRecipient":"3",
"Numbers":
{
"num1":9898776568,
"num2":9087674589
},
"Msg":"This is a test"
}
and in Server I have a class to handle this JSON as below:
public class SmsData
{
public int Id { get; set; }
public int ClientId { get; set; }
public int NoOfRecipient { get; set; }
public IEnumerable<Numbers> Numbers { get; set; }
public string Msg { get; set; }
public DateTime SentDate { get; set; }
}
public class Numbers{
public int Id { get; set; }
public long Number { get; set; }
}
[Table("SmsData")]
public class StoreSmsData
{
public int Id { get; set; }
public int ClientId { get; set; }
public int NoOfRecipient { get; set; }
}
[Table("SmsSentNumbers")]
public class SentNumbers
{
public int Id { get; set; }
public int ClientId { get; set; }
public long Numbers { get; set; }
public int NumbersId { get; set; }
public string Msg { get; set; }
public DateTime SentDate { get; set; }
}
and Controller is:
public HttpResponseMessage Post(SmsData smsData)
{
SmsHandler smsHandler = new SmsHandler();
Clients client = smsHandler.GetClient(smsData.ClientId);
if (client == null)
{
return Request.CreateResponse<SmsData>(HttpStatusCode.NotFound, smsData);
}
else if (smsData.NoOfRecipient > client.SmsAllowed)
{
return Request.CreateResponse<SmsData>(HttpStatusCode.NotAcceptable, smsData);
}
StoreSmsData ssd = new StoreSmsData();
ssd.ClientId = smsData.ClientId;
ssd.NoOfRecipient = smsData.NoOfRecipient;
ssd = dbContext.StoreSmsData.Add(ssd);
dbContext.SaveChanges();
var response = Request.CreateResponse<StoreSmsData>(HttpStatusCode.Created, ssd);
SentNumbers sn = new SentNumbers();
foreach(Numbers num in smsData.Numbers){
sn.ClientId = smsData.ClientId;
sn.Msg = smsData.Msg;
sn.SentDate = smsData.SentDate;
sn.Numbers = num.Number;
sn.NumbersId = num.Id;
dbContext.SentNumbers.Add(sn);
dbContext.SaveChanges();
}
response = Request.CreateResponse<SentNumbers>(HttpStatusCode.Created, sn);
return response;
}
Now when I access the server it returns this Response Message:
{
"Message":"An error has occurred.",
"ExceptionMessage":"Object reference not set to an instance of an object.",
"ExceptionType":"System.NullReferenceException",
"StackTrace":" at System.Web.Http.ApiController.<InvokeActionWithExceptionFilters>d__1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__0.MoveNext()"
}
I cannot understand the problem. How can i store the numbers in a different table. Also when I debugged with break point the Numbers and Msg value is null. How can I Store the number.In Client Side the Post is fine...