I built a straightforward Web API application that allows users to GET
or POST
data. The data consists of a simple array of Strings like ["foo", "bar"]
. However, when I try to send data using the POST
method to the Web API and then make another call to retrieve the data, the previously posted data is no longer there.
How can I retain the data on the server after each POST
request?
This is the relevant code snippet from my server:
[HttpPost]
public HttpResponseMessage Post([FromBody]string value)
{
data.Add(value);
var msg = Request.CreateResponse(HttpStatusCode.Created, "Added element");
msg.Headers.Location = new Uri(Request.RequestUri + "/" + (data.Count - 1).ToString());
return msg;
}
When sending a POST
request with data = John Doe
, it gets added to a List<String>
named data, but it does not persist once I return to the server.
This is how I am making the call to the server:
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(data), // data = "John Doe"
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
In essence, how do I ensure that "John Doe"
remains stored on the server after sending a POST
request, so that the
List<String> data = ["foo", "bar", "John Doe"]
is maintained?