Delete data from D365 in Batch Request, getting the error 'Content-Type' Header is missing - dynamics-crm

I am trying to create an Azure function to delete some data from a Dynamics 365 CE instance. The plan is to use the D365 WebAPI and the Batch Operations request to establish this.
Currently encountering an issue while sending a request after creating the batch request.
I have been referring to this documentation from Microsoft:
https://learn.microsoft.com/en-us/powerapps/developer/common-data-service/webapi/execute-batch-operations-using-web-api
The code looks like:
var batchId = Guid.NewGuid().ToString();
log.LogInformation($"Batch Request Id = {batchId}.");
HttpRequestMessage deleteBatchRequestMessage = new HttpRequestMessage(HttpMethod.Post, "$batch");
deleteBatchRequestMessage.Content = new MultipartContent("mixed", "batch_" + batchId);
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(d365Url);
// Default Request Headers needed to be added in the HttpClient Object
client.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
client.DefaultRequestHeaders.Add("OData-Version", "4.0");
client.DefaultRequestHeaders.Add("Prefer", "odata.include-annotations=\"OData.Community.Display.V1.FormattedValue\"");
d365HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Set the Authorization header with the Access Token received specifying the Credentials
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", d365Token);
HttpResponseMessage response = await client.SendAsync(deleteBatchRequestMessage);
var ass = await response.Content.ReadAsStringAsync();
But I keep getting the exception:
The 'Content-Type' header is missing. The 'Content-Type' header must be specified for each MIME part of a batch message.","ExceptionMessage":"The 'Content-Type' header is missing. The 'Content-Type' header must be specified for each MIME part of a batch message."

Is there any reason why you use WebApi? You can use the SDK and the IOrganizationService handle Everything. This will make your life very easy
http://www.threadpunter.com/azure/using-azure-functions-to-call-dynamics-365/

Related

Getting 502 BadGateway response when posting using HttpClient (.NET) but not when using Postman

I have an API end-point that I need to post to.
Using Postman I do the following:
Set the method to be POST
Add the URL
In the Headers I set: Content-Type to be application/json
In the Body I add my json string
I hit [Send] and get a 200 response with the expected response.
However, in C# .Net Framework 4.8 (LinqPad 5) I do
var c = new HttpClient(); // Disposed of later
c.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string data = #"{ ""a"": ""b"", ""c"": ""d"" }"; // copied from Postman.
HttpContent payload = new StringContent(data, Encoding.UTF8, "application/json");
var msg = new HttpRequestMessage(HttpMethod.Post, new Uri("https://the.url"), UriKind.Absolute)
{
Content = payload,
};
var response = c.SendAsync(msg).GetAwaiter().GetResult(); // It's a synchronous flow
And this responds with a 502 Bad Gateway.
What am I missing...?
I should point out that I need to use the HttpClient and not RestSharp.

Invalid mimetype exception in Spring boot rest call

I am new to both Spring boot and rest calls.
I am trying to consume a rest service and I do not have any information about that rest API except URL. When I hit that URL from a browser I am getting a response as {key:value}. So, I assumed that it is a JSON response.
I am consuming it in spring boot as follows
restTemplate.getForObject(url, String.class) .
This is giving Invalid mime type "content-type: text/plain; charset=ISO-8859-1": Invalid token character ':' in token "content-type: text"
I assume that this error is because response content type is set to text/plain but it is returning JSON format.
EDIT:
Tried this way but did not work.
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>("parameters",headers);
ResponseEntity<String> result = restTemplate.exchange(url,HttpMethod.GET,
entity, String.class);
How to handle and solve it?
You might want to read about the request headers your REST API needs. Content-Type header specifies the media type of the request you're sending to the server. Because you're just getting data from the server you should set the Accept header to the kind of response you want i.e., Accept: application/json.
Unfortunately, you can't set headers using getForObject(). You could try this:
URL url = new URL("Enter the URL of the REST endpoint");
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuffer content = new StringBuffer();
String inputLine;
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
}

MVC to WebAPI- httpclient

I have MVC App and webapi and both are in different projects and mvc app authenticates via webapi using token authentication. I can authenticate via webapi and get the bearer token in MVC.But when i pass the bearer token to webapi and access resources which are protected by authorize keyword , it throws unauthorized 401 response. Iam using httpclient within MVC to communicate to webapi
1) Using fiddler i can login to webapi and access the webapi resouces using bearer token and authorization working properly.
2) using console app , i can login to webapi and access the webapi resources using bearer token and httpclient works properly
3) using a different MVC project and access the webapi using httpclient gives the same unauthorized error.
using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(handler))
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", BearerToken);
string json = JsonConvert.SerializeObject(requestvalue);
System.Net.Http.HttpResponseMessage response = await client.PostAsync(url, new StringContent(json, Encoding.UTF8, "application/json"));
if (response.IsSuccessStatusCode)
{
HttpContent content = response.Content;
if (content != null)
{
value = content.ReadAsAsync<T>().Result;
}
}
}
Can anyone help on this issue?
I'd recommend you to capture the HTTP request sent through the HTTP Client via Fiddler and compare it to the request that was successful.
Even though, you're setting the Authorization header on the http client, I'm not sure if it is sent in the right format required by the Web API unless I inspect the raw HTTP request
Also you can try setting the authorization header, like below.
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + tokenNo);

Google RECAPTCHA always returning error missing-input-response in the response

Google RECAPTCHA always returning error missing-input-response in the response when I try to check the correctness. How does the call to the service go, to the URL https://www.google.com/recaptcha/api/siteverify ?
The format is:
https://…/api/siteverify?secret=[…]&response=[…]&remote_ip=[…]
Make sure that Content-Type is set to application/x-www-form-urlencoded
.Net example
using (HttpClient httpClient = new HttpClient())
{
var response = await httpClient.PostAsync(GoogleVerificationUrl + "?secret=" + ReCaptchaSecretKey + "&response=" + ReCaptchaResponse, new StringContent("", Encoding.UTF8, "application/x-www-form-urlencoded"));
}

HTTP Request in Xamarin

I wrote the following code in Xamarin to connect the Web Server:
var request = WebRequest.Create( "http://srv21.n-software.de/authentication.json") as HttpWebRequest;
// request.Method = "GET";
request.Method = "POST";
request.Headers.Add("name", "demo");
request.Headers.Add("password", "demo");
request.ContentType = "application/x-www-form-urlencoded";
HttpWebResponse Httpresponse = (HttpWebResponse)request.GetResponse();
It connects to the web server and the web server gets the request for "authentication.json", but doesn't get the parameters of the header ("name" and "password").
What is wrong with my code?
Most likely your parameters need to be in the body of the POST request instead of in the headers. Alternatively you might try to use a GET request instead and provide the parameters through the URL, if your server supports it (i.e. http://srv21.n-software.de/authentication.json?name=demo&password=demo).
This worked for me
using System.Net.Http;
string URL = "http://www.here.com/api/postForm.php";
string DIRECT_POST_CONTENT_TYPE = "application/x-www-form-urlencoded";
HttpClient client = new HttpClient();
string postData = "username=usernameValueHere&password=passwordValueHere");
StringContent content = new StringContent(postData, Encoding.UTF8, DIRECT_POST_CONTENT_TYPE);
HttpResponseMessage response = await client.PostAsync(DIRECT_GATEWAY_URL, content);
string result = await response.Content.ReadAsStringAsync();

Resources