Upload the file to CRM using C# and Web API

1.8k Views Asked by At

I am trying to upload a PDF file to the file field in the CRM entity. I followed the following document: https://learn.microsoft.com/en-us/powerapps/developer/data-platform/file-attributes#upload-file-data

Implemented the code of OAuth to generate an Access token using a Client ID and Client Secret. But I am getting a Bad Request as a response.

Entity name: msnfp_request

File field name: bna_file

var fileStream = System.IO.File.OpenRead(<file path>);
var url = new Uri("https://mydev.crm.dynamics.com/api/data/v9.1/msnfp_request(a528f300-7b53-ec11-8c62-0022482a2e7a)/bna_file);

AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/<domain>");
ClientCredential credential = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(<client id>,<client secret>);
AuthenticationResult result = authContext.AcquireToken("https://mydev.crm.dynamics.com/", credential);
using (var req = new HttpRequestMessage(new HttpMethod("PATCH"), url))
{
  req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
  req.Content = new StreamContent(fileStream);
  req.Content.Headers.Add("Content-Type", "application/octet-stream");
  req.Content.Headers.Add("x-ms-file-name", "test.pdf");
  HttpClient Client = new HttpClient();
  using (var response = await Client.SendAsync(req))
  {
   response.EnsureSuccessStatusCode();
  }
 }

What am I doing wrong in the above code?

1

There are 1 best solutions below

0
Arun Vinoth-Precog Tech - MVP On

I will troubleshoot to see if you are able to find out issues step by step.

  1. Make sure the authentication is working after passing the token, as you are not getting 401 it should be fine. But you can do a simple GET request to cross check the connectivity is working
  2. The plural entity name could be a problem. You can find the status code text to see any inner exception like "The resource could not be found". Pls try in case entity plural name is msnfp_requests then it should be like https://mydev.crm.dynamics.com/api/data/v9.1/msnfp_requests(a528f300-7b53-ec11-8c62-0022482a2e7a)/bna_file (wild guess :))