martes, 1 de octubre de 2019

Llamar a una API desde una aplicacion MVC con C#

A continuación se detallan el respectivo Modelo, Vista y Controlador de mi aplicación MVC creada con C#.

Modelo:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Floreria.Models
{
public class Flor
{
public string Codigo { get; set; }
public string Nombre { get; set; }
public string Origen { get; set; }
}
}

Vista:

@model IEnumerable<Floreria.Models.Flor>
@{
ViewData["Title"] = "FloresAPI";
}
<h2>FloresAPI</h2>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Codigo)
</th>
<th>
@Html.DisplayNameFor(model => model.Nombre)
</th>
<th>
@Html.DisplayNameFor(model => model.Origen)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Codigo)
</td>
<td>
@Html.DisplayFor(modelItem => item.Nombre)
</td>
<td>
@Html.DisplayFor(modelItem => item.Origen)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</tbody>
</table>

Controlador:

namespace Floreria.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult FloresAPI()
{
IEnumerable<Flor> flores = null;
using (var client = new HttpClient())
{
var _clientBaseUrl = client.BaseAddress = new Uri("https://dmq9re9bpi.execute-api.us-west-2.amazonaws.com/test/flor");
//HTTP GET
var responseTask = client.GetAsync(_clientBaseUrl);
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsAsync<IList<Flor>>();
readTask.Wait();
flores = readTask.Result;
}
else //web api sent error response
{
//log response status here..
flores = Enumerable.Empty<Flor>();
ModelState.AddModelError(string.Empty, "Server error. Please contact administrator.");
}
}
return View(flores);
}
}
}

No hay comentarios:

Publicar un comentario