学习.net核心3.1-首次尝试使用API​​网络服务

时间:2020-06-25 12:36:29

标签: c# .net json api

我是.net core 3.1的新手-暂时没有很多经验-我有20年使用IBMi上的过程语言进行软件开发的经验。一直在学习教程,以使用我在IBMi上创建的API ...我被困住了...

下面是我的HomeController ...到目前为止,我可以通过运行此代码来完成...

1。)连接到我的IBMi端点

2。)它确实调用了正确的后端API pgm

3。)后端API pgm确实确实从URI中获取了json字符串并按应有的方式对其进行处理,并产生了json字符串响应。

问题..

1。)最终,我想在主体中传递此json请求字符串,而不是URI

2。)在一切都可以通过URI传递json字符串的情况下,当json字符串响应被发回时,处理该响应存在问题。我的猜测是,它期望返回json对象而不是字符串。 错误是...

JsonException:JSON值无法转换为 System.Collections.Generic.IEnumerable`1 [coreiWS.Models.ProductKey]。 路径:$ |行号:0 | BytePositionInLine:1。

生成的json字符串响应为...(或也可以包含试用键值-尽管如此,两者均为字符串格式的有效json)...

{ “成功”:0, “ resultMessage”:“错误RST00001R-无效-产品代码已授予2个试用密钥。请给我们发送电子邮件至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);

1 个答案:

答案 0 :(得分:0)

您的JSON似乎返回一个奇异的对象,但是您试图将其映射到console.log(Object.getPrototypeOf(team["First Base"])) console.log(Object.getPrototypeOf(team.Catcher))

这可能使您理解第一条错误消息。