繁体   English   中英

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

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

我正在尝试将 PDF 文件上传到 CRM 实体中的文件字段。 我遵循以下文档: https://docs.microsoft.com/en-us/powerapps/developer/data-platform/file-attributes#upload-file-data

实现了 OAuth 的代码,以使用客户端 ID 和客户端密码生成访问令牌。 但我收到了一个错误的请求作为回应。

实体名称:msnfp_request

文件字段名: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();
  }
 }

我在上面的代码中做错了什么?

我将进行故障排除,看看您是否能够逐步找出问题。

  1. 确保通过令牌后身份验证正常工作,因为您没有得到 401 应该没问题。 但是您可以执行一个简单的 GET 请求来交叉检查连接是否正常
  2. 复数实体名称可能是个问题。 您可以找到状态代码文本以查看任何内部异常,例如“找不到资源”。 请尝试如果实体复数名称是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