Using Visual Code I created a web service for D365BC.
In MS Visual Studio I use the following code to read data from this web service (so far so good):
private void button1_Click(object sender, EventArgs e)
{
string _url = "">api.businesscentral.dynamics.com/.../WorkersWebService";
HttpWebRequest _request = (HttpWebRequest)WebRequest.Create(_url);
_request.ContentType = "application/json; charset=utf-8";
_request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes("USERNAME:PASSWORD"));
_request.PreAuthenticate = true;
HttpWebResponse _response = _request.GetResponse() as HttpWebResponse;
using (Stream _responseStream = _response.GetResponseStream())
{
StreamReader _reader = new StreamReader(_responseStream, Encoding.UTF8);
string _content = _reader.ReadToEnd();
string _jasonPart = GetJsonPartMultiRecord(_content);
List<WorkerClass> _jWorkers = JsonConvert.DeserializeObject<List<WorkerClass>>(_jasonPart);
foreach (var _worker in _jWorkers)
{
WorkersReadFromAlWebService.Add(_worker);
}
}
}
Now I would like to alter a value from a record or create a new record (using ODATA)
I tried something like this:
private void btnUpdateWS_Click(object sender, EventArgs e)
{
string _url = "">api.businesscentral.dynamics.com/.../WorkersWS";
HttpWebRequest _request = (HttpWebRequest)WebRequest.Create(_url);
_request.ContentType = "application/json; charset=utf-8";
_request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes("USERNAME:PASSWORD"));
_request.Accept = "*/*";
_request.KeepAlive = true;
//_request.Method = "PUT";//error 405: Method is not allowed
_request.Method = "PATCH";//error 405: Method is not allowed
string _etag = rtbE_Tag.Text;
_request.Headers["If-Match"] = String.Format("W/\"{0}\"", _etag);
//_request.Method = "POST";//error 400: invalid method
string body = "{" + Environment.NewLine +
"\"No\":" + tbNo.Text + "," + Environment.NewLine +
"\"First_name\":\"" + tbFirstName.Text + "\"," + Environment.NewLine +
"\"Last_Name\":\"" + tbLastName.Text + "\"," + Environment.NewLine +
"\"FunctionName\":\"" + tbFunctionName.Text + "\"," + Environment.NewLine +
"}";
byte[] data = Encoding.ASCII.GetBytes(body);
_request.ContentLength = data.Length;
Stream requestStream = _request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
HttpWebResponse _response = _request.GetResponse() as HttpWebResponse;
Console.WriteLine(_response.StatusCode);
}
It doesn't matter if I use Patch or Put in both cases I get: error 405: Method is not allowed?
Using a POST (setting Patch, Put and the request headers above the POST as comment) I get error 400 invalid method
I would like to find a way using ODATA to update and or create a new record.
What am I doing wrong??
Kind regards,
Clemens Linders