简体   繁体   中英

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.

So, I need to get information about cryptocurrencies using coinmarketcap.com API and display them in the table. I created controller class and used the example code from API documentation:

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? Should I keep client.DownloadString(URL.ToString()); or use json instead of string? Also my guess is that I should create the cryptocurrency model which will contain name, symbol, date_added and other.

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 :

// GET: CryptoCurrency
public ActionResult Index()
{
    var str = MakeAPICall();
    var viewModel = JsonConvert.Deserialize<YourViewModel>(str);
    return View(viewModel);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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