Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Customer experience | Sales, Customer Insights,...
Answered

WebApi to create record in console application failing due to bad request error

(0) ShareShare
ReportReport
Posted on by 50

Hello everyone,

I need your help in resolving an issue. I have created a console application which talks to the Dynamics 365 9.2 online instance, creates a record. I have created the app, secret and established the connection with the environment. However, I am not able to create the record. It says bad request. Please help.

using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Crm.Sdk.Messages;
using System.Net;
using System.ServiceModel.Description;
using Microsoft.Xrm.Tooling.Connector;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Net.Http.Headers;
using System.Net.Http;
using Newtonsoft.Json.Linq;

namespace GMG_QB_Integration
{
    class Program
    {
        static void Main(string[] args)
        {
            String url = "orgname.crm.dynamics.com";
            string clientId = "00000000-0000-0000-0000-000000000000";
            string secret = "zzzzzzzzzzzzzzzzzzzzzzzzz";
            AuthenticationContext authContext = new AuthenticationContext("login.microsoftonline.com/00000000-0000-0000-0000-000000000000");
            ClientCredential credential = new ClientCredential(clientId, secret);
            AuthenticationResult authResult = authContext.AcquireToken(url, credential);
            string apiVersion = "9.2";
            string webApiUrl = $"{url}/api/data/v{apiVersion}/";
            var authHeader = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(webApiUrl);
                client.DefaultRequestHeaders.Authorization = authHeader;
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Add("Prefer", "odata.include-annotations = *");
                // Use the WhoAmI function
                var response = client.GetAsync("WhoAmI").Result;

                if (response.IsSuccessStatusCode)
                {
                    //Get the response content and parse it.  
                    JObject body = JObject.Parse(response.Content.ReadAsStringAsync().Result);
                    Guid userId = (Guid)body["UserId"];
                    Console.WriteLine("Your UserId is {0}", userId);
                    Task.WaitAll(Task.Run(async () => await CreateContactOld(client)));

                }
                else
                {
                }               

            }

        }
        static async Task CreateContactOld(HttpClient httpClient)
        {
            string jobCreateuri = string.Empty;
            JObject jobCreate = new JObject();
            jobCreate.Add("sa_name", "Test");
            HttpRequestMessage request1 = new HttpRequestMessage(HttpMethod.Post, ".../sa_jobs");
            request1.Content = new StringContent(jobCreate.ToString(), System.Text.Encoding.UTF8, "application/json");
            HttpResponseMessage response1 = await httpClient.SendAsync(request1);
            if (response1.StatusCode == HttpStatusCode.NoContent)
            {
                Console.WriteLine("Job created" + jobCreate.GetValue("sa_name"));
                HttpResponseHeaders responseheaders = response1.Headers;
                jobCreateuri = responseheaders.Location.AbsoluteUri;
            }
            else
            {
                Console.WriteLine("failed to create job");
            }

        }
    }

}
  • Verified answer
    mobeenmohsin Profile Picture
    mobeenmohsin on at
    RE: WebApi to create record in console application failing due to bad request error

    Hi, 

    Please help to see following example 

    https://sank8sinha.wordpress.com/using-calling-dynamics-365-web-api-for-integration-and-console-application/

    We have verified and it is working fine, thank you. 

    Best Regards,

    Mobeen Mohsin

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Daivat Vartak – Community Spotlight

We are honored to recognize Daivat Vartak as our March 2025 Community…

Announcing Our 2025 Season 1 Super Users!

A new season of Super Users has arrived, and we are so grateful for the daily…

Kudos to the February Top 10 Community Stars!

Thanks for all your good work in the Community!

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 292,516 Super User 2025 Season 1

#2
Martin Dráb Profile Picture

Martin Dráb 231,432 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans