How to consume webAPI REST ASP.NET MVC [closed]

0

Well, this is what I'm developing, a Service Rest and an application that will consume this web-service (VIA BROWSER EVEN).

Inmyproject,Ihavethemodel(inthecaseofmyOracledatabase),mycontrolerProductsController.cssthathasgetmethodgetproductname.

The web-service is working fine (Example: postman photo).

Doubt:

I'm just wondering how to consume this web-service, it will return a json, I would like to generate a view with table (GridView) in MVC with the name of each product in case.

    
asked by anonymous 14.02.2018 / 19:35

1 answer

1

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>
    
16.02.2018 / 16:19