【问题标题】:Exception using dynamics 365 web Api Console使用 dynamics 365 web Api 控制台的异常
【发布时间】:2017-11-28 15:44:43
【问题描述】:

我正在尝试使用 web-api 在 Dynamics 365/CRM 上创建一些记录。它在进行 GUID 检索时起作用。

在我的场景中,我应该通过 webservices 使用来自 azure 的 web api。当它被调用时,它应该查询实体 Lead Sources 并在实体 Lead 上设置 GUID。

获取查询结果时出现错误。

这是我的代码:

  using System;
  using System.Net;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Threading.Tasks;
  using Microsoft.IdentityModel.Clients.ActiveDirectory;
  using System.Net.Http;
  using System.Net.Http.Headers;
  using Newtonsoft.Json.Linq;
  using Newtonsoft.Json;

 namespace Integration.Marketing_Activities_Creation
   {
 class Create
 {
    List<string> entityUris = new List<string>();
    string LeadSource1Uri;

    static void Main(string[] args)
    {
        Create.RunAsync().Wait();
    }

    public static async Task RunAsync()
    {

        String clientId = "0000000-0000-0000-0000-00000000";
        String redirectUrl = "http://localhost";
        String user = "new@organization.onmicrosoft.com";
        String pass = "********";
        String baseAddress = "https://crm-instance.api.crm.dynamics.com/api/data/";
        String baseAddressFull = baseAddress + "v8.2/";

        AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(
                    new Uri(baseAddress)).Result;

        //List<string> entityUris = new List<string>();

        String authorityUrl = ap.Authority;
        String resourceUrl = ap.Resource;

        AuthenticationContext authContext = new AuthenticationContext(authorityUrl, false);
        UserCredential credentials = new UserCredential(user, pass);
        AuthenticationResult result;
        result = authContext.AcquireToken(resourceUrl, clientId, credentials);
        // = authContext.AcquireToken(resource, clientId, new Uri(redirectUrl));
        var token = result.AccessToken;

        var client = new HttpClient();
        client.BaseAddress = new Uri(baseAddressFull);
        client.Timeout = new TimeSpan(0, 2, 0);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);

        /*** Create Leads ***/

        string LeadName = "Lead first Name";
        string LeadLastName = "Lead second Name";
        string LeadEmail = "3webapi@lead1.com";
        string LeadTopic = "WebApi Lead 3";
        string LeadSource = "Contact Us";
        HttpResponseMessage response;

        string queryLeadSource;

        queryLeadSource = "new_leadsources?$select=new_leadsourceid,new_name&$filter=new_name eq '" + LeadSource + "'";

        string LSId=null;
        response = await client.GetAsync(queryLeadSource,
            HttpCompletionOption.ResponseContentRead);
        if (response.IsSuccessStatusCode)
        {
            JObject lsRetreived = JsonConvert.DeserializeObject<JObject>(await
                response.Content.ReadAsStringAsync());
            LSId = lsRetreived["new_leadsourceid"].ToString(); /*** outgoing on this line i get an exception and the app crashes :( ***/
        }
        else
        {
            Console.WriteLine("Error retrieving tracking Lead Source ID!");
            throw new CrmHttpResponseException(response.Content);
        }

        JObject newLead = new JObject();
        newLead.Add("firstname", LeadName);
        newLead.Add("lastname", LeadLastName);
        newLead.Add("emailaddress1", LeadEmail);
        newLead.Add("subject", LeadTopic);
        newLead.Add("new_leadsource@odata.bind", "/new_leadsources("+ LSId + ")");

        HttpResponseMessage responsePost = await client.PostAsJsonAsync("leads", newLead);

      }
   }
}

【问题讨论】:

  • 你得到的异常是什么?什么是 InnerException,如果有的话?
  • 嗨 Martijn,我收到此消息“对象引用未设置为对象的实例。”字符串,然后运行控制台展开 :D :( 当我在 LSId = lsRetreived["new_leadsourceid"].ToString(); 上检索 GUID 时,它是第 81 行的对象
  • 这里也返回执行 static void Main(string[] args) { Create.RunAsync().Wait(); }
  • 您的查询返回一个实体对象数组。因此lsRetreived["new_leadsourceid"] 返回null 并且.ToString() 抛出NullReferenceException。只需在行上设置一个断点并检查对象lsRetreived
  • 嗨,Henk,不,它不返回 null,它返回我发送的 LeadSource 变量的 GUID

标签: c# asp.net-web-api dynamics-crm


【解决方案1】:

您正在查询new_leadsources,因此您没有得到一条记录,而是得到一个结果数组。更准确地说,如果您调用:

http://apiurl/new_leadsources?$select=new_leadsourceid,new_name&$filter=new_name eq '" + LeadSource + "'"

结果将如下所示(这是简化的):

{
    value: [{
        new_leadsourceid: "guid",
        new_name: "somename"
    }]
}

当然如果你有多个同名记录,你会在这个Array中获得更多的记录,但它仍然是一个Array。

所以在这一行:

LSId = lsRetreived["new_leadsourceid"].ToString();

您正在尝试访问只有“值”属性的对象的“new_leadsourceid”属性。 考虑到响应的结构,您应该执行以下操作:

LSId = lsRetreived["value"][0]["new_leadsourceid"].ToString();

当然,这段代码很糟糕而且容易出错(它假定总是至少有一个结果并且总是取第一个结果),但它应该让你朝着正确的方向前进。

另外 - 使用调试器,它确实有助于了解你的代码发生了什么,根据你的 cmets 我假设你没有花任何时间进行调试。

【讨论】:

  • 嗨,Pawel,感谢您的反馈,我正在使用调试器,但我不是深入 .NET 开发,所以有一些我要理解的东西,但是,在你的例子中,你的意思是我必须设置我需要的值?我的意思是,这样做http://apiurl/new_leadsources?$select=new_leadsourceid&amp;$filter=new_name eq '" + LeadSource 我只查询一个值,所以数组应该只检索一个结果,我应该在LSId = lsRetreived["parameter_needed_example"][0]["new_leadsource"].ToString(); 上使用该参数?
  • 我不确定我是否理解您的问题。再一次 - 看看来自服务的响应是怎样的(JSON 结构)。 “值”不是参数,它只是作为此 JSON 对象中的字段存在。所以我不明白什么是“parameter_needed_example”,应该有那么简单的“值”。您甚至尝试过我发布的代码吗?我为您提供了整行,只需复制粘贴并替换您当前的行...
  • 谢谢帕维尔!我和其他东西在一起,但今天我复制并粘贴你的行,就像一个魅力:D ...只是为了澄清“parameter_needed_example”你是对的,设置“值”有效,设置实体的名称没有,这是我的错:D
猜你喜欢
  • 1970-01-01
  • 2017-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-26
  • 1970-01-01
相关资源
最近更新 更多