如何解决如何在 .core 中使用“ReadAsAsync”
我需要使用 cutt.ly URL 更短的 API,我遵循了它的文档以及我如何使用它
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 core 处理这个问题。我找到了这个 question。但我不清楚它的答案。
解决方法
我在 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);
,
创建类并尝试以下代码:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<div class="col-lg-12 col-sm-6 companyBtn" id="3543">
<div class="strip">
<div class="row">
<div class="col-2">
<img class="img-fluid rounded-circle d-inline pr-2" style="max-width: 50px" src="https://i.picsum.photos/id/400/100/100.jpg?hmac=pvDsAYmMO0rcZJDGuhmCPDrPeCkJIkGR90-rqPYCMmw">
</div>
<div class="col-10">
<div class="strip_info seenIcon">
<div class="item_title">
<h3 class="testTitle" style="width:90%;font-size:1.1rem">Test Company</h3>
<small class="d-block mb-3"> <span class="flag-icon flag-icon-gb"></span> United Kingdom</small>
<small class="badge badge-warning">Artist Managers</small>
</div>
</div>
</div>
</div>
</div>
</div>
您必须安装 Newtonsoft.Json nuget 包才能从 json 转换。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。