Here is a basic and robust example:
First create a ViewModel, this is not mandatory but it is a good practice and in the future you will realize the benefits of such.
namespace Exemplo.ViewModels
{
public class ProdutosViewModel {
public List<string> ListaProdutos { get; set; }
public ProdutosViewModel()
{
ListaProdutos = new List<string>();
}
}
}
Then in your Controller
, you query your API, populate the ProductsViewModel, and return to View
namespace Exemplo.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
string ApiBaseUrl = "http://localhost:53568/"; // endereço da sua api
string MetodoPath = "Produtos/GetTodosProdutos"; //caminho do método a ser chamado
var model = new ProdutosViewModel();
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(ApiBaseUrl + MetodoPath);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var retorno = JsonConvert.DeserializeObject<List<string>>(streamReader.ReadToEnd());
if (retorno != null)
model.ListaProdutos = retorno;
}
}
catch (Exception e)
{
throw e;
}
return View(model);
}
}
}
Finally, in your% index, you declare the ProductsViewModel as your @Model and display the list of products obtained from your API on the Controller. In your case since I wanted to create a table with the name of the products, it follows a very basic example even just for demonstration
@model Exemplo.ViewModels.ProdutosViewModel
@{
Layout = null;
}
<div>
@if (Model.ListaProdutos != null && Model.ListaProdutos.Count > 0)
{
<table>
@foreach (var prod in Model.ListaProdutos)
{
<tr>
<td>@Html.Raw(prod)</td>
</tr>
}
</table>
}
</div>