【问题标题】:Business Central APIConnect With Xamarin Forms using Azure AD业务中心 APIConnect 与使用 Azure AD 的 Xamarin Forms
【发布时间】:2021-07-08 09:50:03
【问题描述】:
public class EmployeeAbsenceService
{
    private HttpClient _client;
    private readonly string webAPI = "https://xxxxxx";

    public async Task<ObservableCollection<EmployeeAbsence>> GetData()
    {
        var uri = new Uri(webAPI);
        var myToken = await SecureStorage.GetAsync("AccessToken");

        HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Get, uri);
        message.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", myToken);
        try
        {
            HttpResponseMessage response = await _client.SendAsync(message.ToString());
            if(response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<ObservableCollection<EmployeeAbsence>>(content);
            }
        }
        catch(Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(ex.ToString());
        }
        return null;
    }
}

我使用安全存储访问令牌,它工作正常。

我正在尝试从业务中心获取数据,但错误消息:

System.NullReferenceException:对象引用未设置为对象的实例

【问题讨论】:

  • 你能添加异常的堆栈跟踪吗?
  • 哪一行抛出异常?
  • @Cheesebaron HttpResponseMessage response = await _client.SendAsync(message);
  • 您在哪里创建_client 的实例?
  • 私有 HttpClient _client; @Cheesebaron

标签: c# .net xamarin asp.net-web-api


【解决方案1】:

System.NullReferenceException:对象引用未设置为实例 一个对象

您正在尝试使用空值。这意味着您要么将其设置为 null,要么根本不将其设置为任何值。

从您发布的代码中,我们发现您创建了变量_client,但您在使用之前没有为其赋值:

HttpResponseMessage response = await _client.SendAsync(message.ToString());

因此,您可以在使用它之前为其分配一个新实例,例如:

_client = new HttpClient ();

【讨论】:

  • 嗨@MuthuKumar K,我已经好几天没有收到你的消息了。如果有什么我可以在这里提供帮助的,请告诉我。
猜你喜欢
  • 2020-06-01
  • 1970-01-01
  • 2020-09-03
  • 1970-01-01
  • 1970-01-01
  • 2017-09-04
  • 2017-11-02
  • 1970-01-01
  • 2021-05-09
相关资源
最近更新 更多