I'm working with JSON for a while now, but this is a problem I can't solve.
The program is written in C# and has a method called CreateWebRequest():
public void CreateWebRequest()
{
CurrentTime = DateTime.Now;
target = link;
request = WebRequest.Create(target) as HttpWebRequest;
request.ContentType = "application/json; charset=utf-8";
request.Method = "PUT";
request.ServicePoint.Expect100Continue = false;
string postData = jsonString;
System.Console.WriteLine("POSTDATA: " + postData);
StreamWriter requestWriter;
using (requestWriter = new StreamWriter(request.GetRequestStream()))
{
requestWriter.Write(postData);
}
}
The other function to fetch the result is called: CreateWebResponse():
public void CreateWebResponse()
{
WebResponse response;
string text;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException e)
{
MessageBox.Show(e.Message);
return;
}
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
APIresult apiresult = JsonConvert.DeserializeObject<APIresult>(text); //Deserialize the text
}
These functions work all fine, there is only one problem: the code does two requests.
When I put the same JSON in the RESTClient in mozilla FireFox the JSON works fine. It also works great when I'm only using CreateWebRequest(), but when I use both of the methods it seems the code creats a second request?
Is it possible to create only a response? Combine these two functions to one which creates directly an response?
I tried other solutions and put them just together, none of them seems to work. When I call for a response the code doesn't work properly anymore and creates two requests.
Has anyone a solution?
Thanks in advance.
The JSON function I call has several if statements and work fine according to RESTClient in Firefox. The code below shows the code which is called correct by RESTClient and twice by the C# code:
$sql = 'SELECT...';
$result = $db->sql_query($sql);//search for member id.
if($row = $db->sql_fetchrow($result)){//when found, the user has access.
$member_id = $row['member_id'];
$sql = 'SELECT ...';
$result = $db->sql_query($sql);//search for last login today.
if($row = $db->sql_fetchrow($result)){//if the user has logged in today update the row.
$row_check_in_timestamp = $row['check_in_timestamp'];
$sql = 'UPDATE ...';//update the row with the check out timestamp
$db->sql_query($sql);
break;
}else{//the user hasn't logged in yet today, log in.
$start_session_array = array(
'club_id' => (int)$club_id,
'member_id' => (int)$member_id,
'check_in_timestamp' => (int)time(),
);
$sql = 'INSERT ...';//check user in and add a new row in the database
$db->sql_query($sql);
break;
}
}else{
break;
}