使用 Postman 从 API 检索的数据与使用 C# 程序时不同

问题描述 投票:0回答:1

我使用 postman 从 sigfox API 检索的数据与我使用 http 客户端使用 C# 程序时获取的数据不同。

API 包含查询参数,例如:

  • limit=(a number) -- 限制我可以接收的消息数量的数字(不影响问题)

  • 之前 = (unix 时间)
  • since=(unix 时间) 这是时间参数。

在邮递员中,我收到的数据遵循时间参数,这意味着收到的数据是在设置时间之前和设置时间之后。

Api链接(带有虚假信息): https://backend.sigfox.com/api/devicetypes/devicetpes-id(filler)/messages?limit=100&before=1568186400&since=1568185800

这是数据的下载部分:

public static class DownloadData
{
    private static string UrlParameters="?limit=100&before=&since=";
    public static void GetfromAPI(string deviceId, long beforeTime, long sinceTime)
    {
        var apiResponse = new Models.Datas();
        var baseUrl = ConfigurationManager.AppSettings["ApiBaseUrl"];
        var username = ConfigurationManager.AppSettings["ApiUserName"];
        var password = ConfigurationManager.AppSettings["ApiPassword"];
        var mediatype = ConfigurationManager.AppSettings["MediaType"];
        var finalUrl = string.Format(baseUrl, deviceId, beforeTime, sinceTime);
        using (var client = new ApiClient(finalUrl, username, password, mediatype))
        {
            //apiResponse = client.GetAsyncMessage<Models.Datas>(UrlParameters).Result;
            apiResponse = client.GetAsyncMessage<Models.Datas>(UrlParameters).Result;
            InsertToDatabase(FormatData(apiResponse.Data)); //apiresponse.data is holding the data

        }
    }

http 客户端

public class ApiClient : IDisposable
{
    private HttpClient _httpClient;
    private readonly string _baseurl;
    private readonly string _username;
    private readonly string _password;
    private readonly string _mediatype;


    public ApiClient(string baseurl, string username, string password , string mediatype)
    {
        _baseurl = baseurl;
        _username = username;
        _password = password;
        _mediatype = mediatype;
    }

    public async Task<TResult> GetAsyncMessage<TResult>(string url) where TResult : class, new()

    {
        var strResponse = await GetAsyncMessage(url);



        return JsonConvert.DeserializeObject<TResult>(strResponse, new JsonSerializerSettings ///str respons holding the string 
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        });
    }

    private async Task<string> GetAsyncMessage(string url)
    {
        CheckHttpClientConnection();

        using (var response = await _httpClient.GetAsync(url))
        {
            response.EnsureSuccessStatusCode();
            return await response.Content.ReadAsStringAsync();


        }
    }

具有基本身份验证的httpclient

private void CreateHttpClient()
    {
        _httpClient = new HttpClient { BaseAddress = new Uri(_baseurl) };
        byte[] cred = UTF8Encoding.UTF8.GetBytes(_username + ":" + _password);
        _httpClient.DefaultRequestHeaders.Authorization =
            new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(cred));
        _httpClient.DefaultRequestHeaders.Accept.Add(
            new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(_mediatype));
    }

另一个文件中运行顶部代码的函数

DownloadData.GetfromAPI("devicetypesid filler",Common.BCurrenttimetoUnix(), Common.SCurrenttimetoUnix());

the common.bcurrentimetounix etc is taking the value from the function as the before and since query parameters.

所以我在邮递员中获得的数据遵循查询参数。这意味着我得到的数据是在之前和之后的时间范围内。

示例:

下午 4.50 之前,自下午 4.40 起是为参数设置的时间。

检索到的数据是第 1 个数据 = 4.49pm,第 100 个数据 = 4.41pm。

但是在我的 C# 程序中它甚至不遵循参数。检索到的数据超出计时之后和之前的数据。

编辑#1。图片

编辑#2

基本网址:

<add key="ApiBaseUrl" value="https://api.sigfox.com/v2/device-types/{0}/messages" />

编辑#3

将此作为基本网址: 调试截图:

  <add key="ApiBaseUrl"  value="https://api.sigfox.com/v2/device-types/{0}/messages?limit=100&amp;before={1}&amp;since={2}" />

编辑#4

此代码正在运行。


        public static void GetfromAPI(string deviceId, long beforeTime, long sinceTime)
        {
            var apiResponse = new Models.Datas();
            var baseUrl = ConfigurationManager.AppSettings["ApiBaseUrl"];
            var username = ConfigurationManager.AppSettings["ApiUserName"];
            var password = ConfigurationManager.AppSettings["ApiPassword"];
            var mediatype = ConfigurationManager.AppSettings["MediaType"];
            var urlparam = ConfigurationManager.AppSettings["ApiParam"];
                
            var finalurl = string.Format(baseUrl, deviceId);
            var urlParam = $"?limit=100&before={beforeTime}&since={sinceTime}";

            using (var client = new ApiClient(finalurl, username, password, mediatype))
            {
                //apiResponse = client.GetAsyncMessage<Models.Datas>(UrlParameters).Result;
                apiResponse = client.GetAsyncMessage<Models.Datas>(urlParam).Result;
                InsertToDatabase(FormatData(apiResponse.Data)); //apiresponse.data is holding the data

            }
c# postman dotnet-httpclient
1个回答
1
投票

您正在设置

UrlParameters
变量,而没有
before
since
的值:-

private static string UrlParameters="?limit=100&before=&since=";

并且您在发送之前没有更新;在您设置

finalUrl
的位置,您的
string.Format
不引用
UrlParameters
;因此,您获得的值超出了指定的
beforeTime
afterTime

尚不清楚您使用的是什么 ApiClient,但是,这里有一个使用基本

WebClient
的示例:-

var baseUrl = "https://backend.sigfox.com/api/devicetypes";
var deviceId = "12345";
var before = 1568186400;
var since = 1568185800;

var url = $@"{baseUrl}/{deviceId}/messages?limit=100&before={before}&since={since}";

var json = new System.Net.WebClient().DownloadString(url);

编辑

尝试像这样更新您的

GetfromAPI
方法(我已经修复了
finalUrl
的构造方式,并将其而不是
UrlParameters
传递给您的
GetAsyncMessage
方法,并且我将
baseUrl
而不是
finalUrl
传递给您的
ApiClient
构造函数):-

public static class DownloadData
{
    public static void GetfromAPI(string deviceId, long beforeTime, long sinceTime)
    {
        var apiResponse = new Models.Datas();
        var baseUrl = ConfigurationManager.AppSettings["ApiBaseUrl"];
        var username = ConfigurationManager.AppSettings["ApiUserName"];
        var password = ConfigurationManager.AppSettings["ApiPassword"];
        var mediatype = ConfigurationManager.AppSettings["MediaType"];

        var finalUrl = $"api/devicetypes/{deviceId}/messages?limit=100&before={beforeTime}&since={sinceTime}";

        using (var client = new ApiClient(baseUrl, username, password, mediatype))
        {
            apiResponse = client.GetAsyncMessage<Models.Datas>(finalUrl).Result;
            InsertToDatabase(FormatData(apiResponse.Data)); //apiresponse.data is holding the data
        }
    }
}

注意:您可能需要摆弄

finalUrl
,具体取决于您的
baseUrl
设置为什么(我在这里看不到);我们的想法是在将
url
值传递给
HttpClient
之前检查它,以便您可以确认它正在尝试获取什么。

© www.soinside.com 2019 - 2024. All rights reserved.