繁体   English   中英

如何在asp.net c#中获取API响应

[英]how to get API response it in asp.net c#

我有以下 API json 请求

 "myjsonrequest": {
                        "ServiceKey": "Hello",
                        "Identityvals": {
                                        "IDName": "regnum",
                                        "IDValue": "112233"
                        }
        }

任何获得响应的简单方法,我使用 ASP.net c#

我试过这个代码

 HttpClient client = new HttpClient();
            string x = "{'IDName','regnum'},{'IDValue','112233'}";
            var Keys = new Dictionary<string, string>
            {
                   { "ServiceKey", "hello" },
                   { "PractitionerIdentity",x}
                };

        var content = new FormUrlEncodedContent(Keys);
        var response = await client.PostAsync("https://apiurl", content);
        var responseval = await response.Content.ReadAsStringAsync();

尝试这个 :

var json = new {
          ServiceKey = "",
          PractitionerIdentity = new {
              IDName = "" ,
              IDValue = ""            
           }  
         };
HttpClient client = new HttpClient();
var content = new StringContent(json, Encoding.UTF8, "application/json")
var response = await client.PostAsync("https://apiurl", content);

您的 Json 数据应按以下方式保存到模型中:

    public class YourJsonData{
        public string ServiceKey {get; set;}
        //add other names
    } 

最好的一点是,如果你调用你的对象,你会得到一个变量,以便于使用。

然后您可以将其添加到任务中:

    public async Task<List<YourJsonData>> GetJsonAsync(CancellationToken  cancellationToken = default)
    {
        using (var client = new HttpClient())
        {
            //Make the request, and ensure we can reach it
            var response = await client.GetAsync(yourJosnUrl, cancellationToken);
            if (response.IsSuccessStatusCode)
            {
                //Read the actual stream (download the content)
                var content = await response.Content.ReadAsStringAsync();

                //Make sure we do have some valid content before we try to deserialize it
                if (string.IsNullOrEmpty(content))
                {
                    return new List<YourJsonData>();
                }

                //Deserialize into a list of yourjsondata
                return JsonConvert.DeserializeObject<List<YourJsonData>>(content);
            }
        }
        return new List<YourJsonData>();
    }

另外,如果你很懒,你可以用动态替换 YourJsonData。 这里的缺点是你将无法看到你所崇敬的东西。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM