【问题标题】:How to use “ReadAsAsync” in .core如何在 .core 中使用“ReadAsAsync”
【发布时间】:2021-04-24 16:49:32
【问题描述】:

我需要使用 cutt.ly URL 较短的 API,我遵循了它的文档以及我使用它的方式

Cutt.ly documentation

class Program
{
    private const string URL = "https://cutt.ly/api/api.php";
    private static string urlParameters = "?key=ddbbdd323230fbf3e0b9&short=https://www.google.com&name=Test";
    static void Main(string[] args)
    {
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri(URL);

        client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response = client.GetAsync(urlParameters).Result;.
        if (response.IsSuccessStatusCode)
        {
            var dataObjects = response.Content.ReadAsAsync().Result;
            foreach (var d in dataObjects)
            {
                Console.WriteLine("{0}", d.ToString());
            }
        }
        else
        {
            Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
        }

        client.Dispose();
        Console.ReadLine();
    }
}

但问题是我得到以下编译错误。

'HttpContent' does not contain a definition for 'ReadAsAsync' and no accessible extension method 'ReadAsAsync' accepting a first argument of type 'HttpContent' could be found

我正在使用 .net 核心。我如何使用 .net 核心来处理这个问题。我找到了这个question。但我不清楚它的答案。

【问题讨论】:

  • that question 中的答案可能与这个问题的答案相同。要么拉入 nuget 包,要么创建自己的扩展方法来反序列化 System.Text.Json
  • 这与您的问题没有直接关系,您可能已经知道 - 但您可以让您的 Main 返回 async Task,这将允许您等待示例中的异步调用 - @ 987654324@
  • @devNull 你能帮帮我吗,我怎样才能为我的问题应用这个答案?

标签: c# json .net-core httpclient


【解决方案1】:

我在here 之前做过这个 您必须安装 Newtonsoft.Json nuget 包

CuttlyApiKey 是您的 api 键,SelectedCustomText 是您的链接的自定义名称,如果您不想设置自定义名称,您可以设置 string.empty

public async Task<string> CuttlyShorten(string longUrl)
        {

            try
            {
                string url = string.Format("https://cutt.ly/api/api.php?key={0}&short={1}&name={2}", CuttlyApiKey, HttpUtility.UrlEncode(longUrl), SelectedCustomText);

                using (HttpClient client = new HttpClient())
                using (HttpResponseMessage response = await client.GetAsync(url))
                using (HttpContent content = response.Content)
                {
                    dynamic root = JsonConvert.DeserializeObject<dynamic>(response.Content.ReadAsStringAsync().Result);

                    string statusCode = root.url.status;
                    if (statusCode.Equals("7"))
                    {
                        string link = root.url.shortLink;

                        return link;
                    }
                    else
                    {
                        string error = root.status;
                        
                    }

                }
            }
            catch (Exception ex)
            {
                
            }


            return "error";
        }

用法:

var shortUrl = await CuttlyShorten(url);

【讨论】:

    【解决方案2】:

    如果您只需要一个短链接

    var json = response.Content.ReadAsStringAsync().Result;
    var result=JObject.Parse(json);
    
    var shortLink = result["url"]["shortLink"].ToString();
    

    【讨论】:

    • 是的,我试过了,dataObjects 值显示为{"url":{"status":7,"fullLink":"https:\/\/www.google.com","date":"2021-04-24","shortLink":"https:\/\/cutt.ly\/Test","title":"Google"}} 我怎样才能只得到shortLink
    • 我更新了我的答案。它将是 result.Url.ShortLink;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-12
    • 1970-01-01
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    • 2016-10-22
    相关资源
    最近更新 更多