简体   繁体   English

使用 C# 和 Web API 将文件上传到 CRM

[英]Upload the file to CRM using C# and Web API

I am trying to upload a PDF file to the file field in the CRM entity.我正在尝试将 PDF 文件上传到 CRM 实体中的文件字段。 I followed the following document: https://docs.microsoft.com/en-us/powerapps/developer/data-platform/file-attributes#upload-file-data我遵循以下文档: https://docs.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.实现了 OAuth 的代码,以使用客户端 ID 和客户端密码生成访问令牌。 But I am getting a Bad Request as a response.但我收到了一个错误的请求作为回应。

Entity name: msnfp_request实体名称:msnfp_request

File field name: bna_file文件字段名: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?我在上面的代码中做错了什么?

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.确保通过令牌后身份验证正常工作,因为您没有得到 401 应该没问题。 But you can do a simple GET request to cross check the connectivity is working但是您可以执行一个简单的 GET 请求来交叉检查连接是否正常
  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:))请尝试如果实体复数名称是msnfp_requests那么它应该像https://mydev.crm.dynamics.com/api/data/v9.1/msnfp_requests(a528f300-7b53-ec11-8c62-0022482a2e7a)/bna_file (wi猜测:))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM