Consuming a service from the web api in mvc?

2

I am trying to consume web service api via httpwebrequest and razor to show it in mvc view. in the mvc controller I have this code in which I want to consume the api

using EntradaElectronicaAlmacenApi.Services;
using System.IO;
using System.Net;
using System.Web.Mvc;

namespace EntradaElectronicaAlmacen.Controllers
{
    public class InicioController : Controller
    {
        // GET: Inicio
        public ActionResult Index()
        {
            return View();
        }

        // get: opciones
        public ActionResult PantallaOpciones()
        {
            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("http://localhost:49851/api/motivo/motivos");
            myReq.ContentType = "application/json";
            var response = (HttpWebResponse)myReq.GetResponse();
            string text;
            using (var sr = new StreamReader(response.GetResponseStream()))
            {
                text = sr.ReadToEnd();
            }
            var motivos = new MotivoService();
            var result = motivos.ObtenerMotivos();
            var rr = Json(new { motivos = text });
            ViewData["motivos"] = rr;
            return View();



        }
    }
}

and in the view I want to generate some buttons with the data that I want to consume from the api I have the following code.

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Pantalla Opciones</title>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <link href="~/Styles.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-3.3.1.min.js"></script>
    <script src="~/Scripts/bootstrap.js"></script>
</head>
<body>
<div>
@if (ViewData["motivos"] != null)
                    {
                        foreach (var motivo in ViewData["motivos"] as List<EntradaElectronicaAlmacenApi.Infraestructura.Motivos>)
                        {
                            <div class="col-sm-3">
                                <button id="@motivo.Motivo_Id.ToString()-btn" class="boton3d2" data-toggle="modal" data-target="#PopUpAcceso">@motivo.Descripcion</button>
                            </div>
                        }
                    }
</div>
</body>

but it generates the following error

  

An exception of type 'System.InvalidOperationException' occurred in   EntryElectronicaAlmacenApi.dll but was not handled in user code

     

Additional information: No connection string named   'EntryElectronicaAlmacenEntities' could be found in the application   config file.

what could be the error that I investigated and I can not find ...

    
asked by Reyes 27.03.2018 в 03:43
source

2 answers

2

I enclose my solution to the problem that I planted previously in case someone arrives at some point to need it.

private readonly WebApi _webApi;
        public InicioController()
        {
            _webApi = new WebApi("http://localhost:49851/api/");
        }

I established a private function in the controller that would allow me to disialize the object since it returned only a list. Then work with httpClient in this way to fill a list and deserialize an object to use the data.

[HttpGet]
        public async Task<ActionResult> PantallaOpciones()
        {
            var response = await _webApi.Get("motivo/motivos");

            if(response.TipoRepuesta != "Error")
            {
                ViewData["Motivos"] = response.Contenido.DeserializeToListEntity<Motivo>();
            }
            return View();           
        }

and in my view of the controller, just change the visualization of the data a little.

 @if (ViewData["Motivos"] != null)
                    {
                        foreach (var motivo in (List<EntradaElectronicaAlmacen.Models.Dtos.Motivo>)ViewData["Motivos"])
                        {
                            <div class="col-sm-3">
                                <button id="@motivo.Motivo_Id.ToString()-btn" class="boton3d5 clMotivo" data-id="@motivo.Motivo_Id" data-toggle="modal" data-target="#PopUpAcceso">
                                    @motivo.Descripcion
                                </button>
                            </div>
                        }
                    }          
      y con eso pude llamar los botones en base a los datos que tenia en mi base de datos
    
answered by 03.04.2018 / 00:10
source
1

Your error means that the connection string name EntradaElectronicaAlmacenEntities is not found in your web.config.

For example, you should have something like that in web.config :

<configuration>  
    <connectionStrings>  
      <clear />  
      <add name="EntradaElectronicaAlmacenEntities"   
       providerName="System.Data.SqlClient"   
       connectionString="aqui_cadena_conexion_valida_a_tu_server_de_base_de_datos" />  
    </connectionStrings>  
  </configuration>  

Note: please do not confuse with the web.config that is in the folder / Views.

    
answered by 27.03.2018 в 04:52