Configure_microsoft_Dynamic_365_Service_API_ASP_NET_CORE_MVC
Configure_microsoft_Dynamic_365_Service_API_ASP_NET_CORE_MVC

How we configure Microsoft Dynamic-365 Services(API) with ASP.Net core MVC

Before going on the code let, we understood how we call it by postman. To call the D-365 service by postman you need to some credentials which is client_id, client_secret, tenet_id and resource. After getting that credentials you can successfully get the result.
To execute in Postman, follow these steps.

step1Open the Postman and go to the Body Section
step2- go to x-www-form-uriencoded
step3- Now type your credentials that you have
step4- go to url and use your own tenet_id
step6- Now you can successfully get the token
step7- Copy the access_token and go to the Authorization header
step8-
Select type -> Bearer Token and paste the copied token into the token
step9- Now you can use your API url and send the request and you got your response .

After getting the successful status 200 by Postman you can achieved that things at the code level to configure it in .net you have to come on your .net project
open the appsettings.json in .net core you get a appsettings.json file by default during creation of the project now you have to configure your credentials in that file like-

"AppSettings": {
    "ClientID": "25fad014-a1af-4.............................",
    "ClientSecrets": "Io08Q~q_ZB.............................",
    "Tenant_Id": "fd7143fa-11.........................",
    "resource": "fd7143fa-1107-4..........................",
}

After that create a class to configure. The best practice is that to always create a class to access the appsettings.json data value otherwise you have to create a constructor of the class to get the data so best practice is that to always create an individual class and call it when you need it. So, create a class and follow that code.

using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Http;
public static class ConfigurationProvider
{
     public static IConfiguration Configuration { get; private set; }
     static ConfigurationProvider()
     {
           Initialize();
      }
     public static void Initialize()
     {
           Configuration = new ConfigurationBuilder()
           .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
           .AddJsonFile("appsettings.json")
           .Build();
    }
} 

After that you can create a separate class where you can code for token generation so create a class like D365ServiceCall
and create a variable private static readonly type to get the details from the appsettings.json file like that

private static readonly string clientid = ConfigurationProvider.Configuration["AppSettings:ClientID"];
private static readonly string ClientSecrets = ConfigurationProvider.Configuration["Appsettings:ClientSecrets"];

Now create a async method for token generation

public async Task<Token> GetToken()
        {
            string result_data = string.Empty;
            using (var client = new HttpClient())
            {
                client.BaseAddress = new                           Uri($"https://login.microsoftonline.com/{tenant_id}/oauth2/token");
                var httpContent = new StringContent($"grant_type=client_credentials&client_secret=" + clientsecret + "&resource=" + resource + "&tenant_id=" + tenant_id + "&bearerToken=undefined&client_id=" + clientid, Encoding.UTF8, "application/x-www-form-urlencoded");
            
                var responseTask = client.PostAsync("", httpContent);
                responseTask.Wait();
                var result = responseTask.Result;
                if (result.IsSuccessStatusCode)
                {
                    result_data = await result.Content.ReadAsStringAsync();
                }
            }
            return JsonConvert.DeserializeObject<Token>(result_data);
        }

after the token generation you need to create another method for api call here you can define your base URL and call that method again and with your api end point and there requestdata

public async Task<Object> PostD365Service(string apiAction, object jsonContent)
        {
            string timesheetbaseurl = "your api base url"
            string BaseAddress = $"{timesheetbaseurl}{apiAction}";
            try
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 |  SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

                var token = await GetToken();

                CServiceStatus cServiceStatus = new CServiceStatus();

                if (token == null)
                {
                    cServiceStatus.ReturnMessage = "Login validate failed. Not able to authenticate. Please try again!!!";
                    cServiceStatus.RequestStatus = HttpStatusCode.Unauthorized;
                    return null;
                }

                using (var client = new HttpClient())
                {
                    try
                    {
                        var jsonContentString = string.Empty;
                        client.BaseAddress = new Uri(BaseAddress);
                        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.access_token);

                      if (jsonContent != null)
                        {
                            jsonContentString = JsonConvert.SerializeObject(jsonContent);
                         }


                        var content = new StringContent(jsonContentString, Encoding.UTF8, "application/json");
                        var responseTask = await client.PostAsync("", content);
                        cServiceStatus.RequestStatus = responseTask.StatusCode;
                        cServiceStatus.ReturnMessage = responseTask.RequestMessage.ToString();

                        if (responseTask.IsSuccessStatusCode)
                        {
                            var resultData = await responseTask.Content.ReadAsStringAsync();
                            cServiceStatus.ReturnJson = resultData;
                            return resultData;
                        }
                    }
                    catch (Exception ex)
                    {
                        cServiceStatus.RequestStatus = HttpStatusCode.ServiceUnavailable;
                        cServiceStatus.ReturnMessage = ex.Message;
                    }
                }
            }
            catch (Exception ex)
            {

            }
            return null;

        }

That is the complete process to call a D-365 api in a .Net core MVC.

Other Posts –

Comments

No comments yet. Why don’t you start the discussion?

    Leave a Reply

    Your email address will not be published. Required fields are marked *