[英]How to get data using API in ASP.NET MVC?
I'm a complete newbie to back-end developing in C# and ASP.NET MVC, so I may guess my question is a bit stupid and sorry for that, but I've spent hours searching information about this and reading documentation and came out with almost nothing. 我是一个完全的新手,可以使用C#和ASP.NET MVC进行后端开发,因此我可能觉得我的问题有点愚蠢,对此感到抱歉,但是我已经花了很多时间搜索有关此信息并阅读文档,然后才发表几乎没有。
So, I need to get information about cryptocurrencies using coinmarketcap.com API and display them in the table. 因此,我需要使用coinmarketcap.com API获取有关加密货币的信息,并将其显示在表格中。 I created controller class and used the example code from API documentation:
我创建了控制器类,并使用了API文档中的示例代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net;
namespace CryptoCurrency.Controllers
{
public class CryptoCurrencyController : Controller
{
private static string API_KEY = "key";
// GET: CryptoCurrency
public ActionResult Index()
{
// here i need to call the makeAPICall() method,
// get data about cryptocurrencies and send it to the view
return View();
}
static string makeAPICall()
{
var URL = new UriBuilder("https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest");
var queryString = HttpUtility.ParseQueryString(string.Empty);
queryString["start"] = "1";
queryString["limit"] = "80";
queryString["convert"] = "USD";
URL.Query = queryString.ToString();
var client = new WebClient();
client.Headers.Add("X-CMC_PRO_API_KEY", API_KEY);
client.Headers.Add("Accept", "application/json");
return client.DownloadString(URL.ToString());
}
}
}
How do I get the data by API and send it to the view correctly? 如何通过API获取数据并将其正确发送到视图? Should I keep
client.DownloadString(URL.ToString());
我应该保留
client.DownloadString(URL.ToString());
or use json instead of string? 或使用json代替字符串? Also my guess is that I should create the cryptocurrency model which will contain name, symbol, date_added and other.
我的猜测也是,我应该创建一个包含名称,符号,date_added和其他名称的加密货币模型。
I don't need exactly the entire code ready, I'll be glad if you just direct me to some understandable for beginners information about my questions, cause right now I'm drowning in all of this information and can't find what I need. 我不需要完全准备好完整的代码,如果您将我引导到一些可以理解的关于我的问题的初学者信息,我会很高兴,因为现在我淹没了所有这些信息并且找不到我需要的。
Thanks! 谢谢!
You have to call the API from your action, then deserialize the string you got to the view model you define and finally pass this view model to your view : 您必须从操作中调用API,然后反序列化您定义的视图模型中获得的字符串,最后将此视图模型传递给视图:
// GET: CryptoCurrency
public ActionResult Index()
{
var str = MakeAPICall();
var viewModel = JsonConvert.Deserialize<YourViewModel>(str);
return View(viewModel);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.