簡體   English   中英

學習 .net 核心 3.1 - 第一次嘗試使用 API webservice

[英]learning .net core 3.1 - very first attempt at consuming API webservice

我是 .net 核心 3.1 的新手 - 沒有很多 oop 經驗期 - 我有 20 年在 IBMi 上使用過程語言的軟件開發經驗。 一直在學習使用我在 IBMi 上創建的 API 的教程……我被卡住了……

下面是我的 HomeController ......到目前為止,我可以通過運行這段代碼來做什么......

1.) 連接到我的 IBMi 端點

2.) 它確實調用了正確的后端 API pgm

3.)后端 API pgm 確實從 URI 中獲取 json 字符串並按應有的方式處理它,並產生 json 字符串響應。

問題..

1.)最終我想在正文中傳遞這個 json 請求字符串而不是 URI

2.) 當一切都在通過 URI 中的 json 字符串進行工作時,當 json 字符串響應被發回時,處理該響應時出現問題。 我的猜測是它期望返回 json object 而不是字符串。 錯誤是...

JsonException:JSON 值無法轉換為 System.Collections.Generic.IEnumerable`1[coreiWS.Models.ProductKey]。 路徑:$ | 行號:0 | 字節位置內線:1。

生成的 json 字符串響應是......(或者也可以包含試用密鑰值 - 盡管如此,兩者都是字符串格式的有效 json)......

{ "success": 0, "resultMessage": "Error RST00001R - Invalid - Product Code Already 2 Trial Keys. 請 Email 我們在 xxxxxxxxxx@gmail.com 使用 CoreiRST 討論您未來的業務需求。" }

導致它的代碼是......

var responseStream = await response.Content.ReadAsStreamAsync();
            productKeys = await JsonSerializer.DeserializeAsync
                <IEnumerable<ProductKey>>(responseStream);

我將非常感謝任何可以幫助指導我朝着正確方向進行這項工作的人。

完整的 HomeController 代碼是...

public class HomeController : Controller
{

    // jhv - add this...
    private readonly IHttpClientFactory _clientFactory;
    public IEnumerable<ProductKey> productKeys { get; set; }
    public HomeController(IHttpClientFactory clientFactory)
    {
        _clientFactory = clientFactory;
    }

    // jhv - add this...
    public async Task<IActionResult> Index()
    {
        //var user = Authenticate().Result;

        //if (user == null)
            //return View();

        var request = new HttpRequestMessage(HttpMethod.Get,
            "http://xxxxxxxxxxxxxxxxxxxxxxxxx/{\"env\":\"xxx\",\"command\":\"getTrialKey\",\"payload\":{\"productCode\":\"MFT  102A08R EPCA 00007\"}}");
        //request.Headers.Add("Authorization", "Bearer " + user.Token);

        request.Headers.Add("Authorization", "Basic xxxxxxxxxxxxxxxxxx");

        //request.Headers.Add("text/plain", "{\"env\":\"xxx\",\"command\":\"getTrialKey\",\"payload\":{\"productCode\":\"MFT  102A08R EPCA 00007\"}}       \r\n");

        var client = _clientFactory.CreateClient();
        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("text/plain"));

        var response = await client.SendAsync(request);

        if(response.IsSuccessStatusCode)
        {
            var responseStream = await response.Content.ReadAsStreamAsync();
            productKeys = await JsonSerializer.DeserializeAsync
                <IEnumerable<ProductKey>>(responseStream);
        }
        else
        {
            productKeys = new List<ProductKey>();
        }


        return View(productKeys);

看起來您的 JSON 正在返回一個奇異的 object,但您正在嘗試將其 map 到IEnumerable<ProductKey>

這可能會讓您通過第一條錯誤消息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM