top of page

LLAMAR UN WEB API C# MVC

Código simple como ejemplo para llamar un API 

using Farmacia.mvc.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Script.Serialization;

 public class Empleado
    {
        public int Id { get; set; }
        public string Nombre { get; set; }
        public string email { get; set; }

    }

 public Empleado GetUnEmpleado(int id)
        {

            string url = @"http://localhost:62555/api/home/GetSingleUser" + "?Id=" + id;
            try
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

                request.Method = "GET";
                string data = String.Empty;
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    Stream dataStream = response.GetResponseStream();
                    StreamReader reader = new StreamReader(dataStream);
                    data = reader.ReadToEnd();
                    reader.Close();
                    dataStream.Close();

                }
                JavaScriptSerializer jss = new JavaScriptSerializer();
                Empleado user = jss.Deserialize<Empleado>(data);
                return new Empleado { Id = user.Id, Nombre = user.Nombre, email = user.email };

            }

            catch (Exception ex)
            {
                throw ex;
            }
        }

Para llamar un web api desde java script

var valor;

function callApi(cualAction, numero, cualParametro) {
        var elUrl = 'http://localhost:52589/api/series/' + cualAction + '?' + cualParametro + '=' + numero;
        $.ajax(
            {

                type: 'GET',
                url: elUrl,
                async:
false,    //de esta forma se ejecuta el api al momento del llamado, y no espera a que carge la pagina
                success: function (data) {
                    valor = data;

                },

                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("some error");

                }
            }
        );
    }

 

NOTA:

Si el web API está alojado en tu mismo projecto, se puede presentar un error al intentar llamarlo por lo que es necesario agregar estas líneas de código en el Web.config de tu proyecto API.

     <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
      </customHeaders>
    </httpProtocol>

 

Otro ejemplo de llamada ajax

Dada la clase Products

  public class Products
    {

        public int Price { get; set; }
        public string Name { get; set; }
        public string Type { get; set; }
        public string Description { get; set; }
    }

Codio gel API a utilizar

   [HttpGet]
        public string Product(int val)
        {

            var products = new Products
            {
                Name = "Men pants",
                Price = 250,
                Type = "Clothes",
                Description = "These are some confortable pants you can use for daily use"
            };
            
            return   JsonConvert.SerializeObject(products);
        }

El Codigo html/javascript para llamar el api seria el siguiente


<button type="submit" class=" btn btn-danger" onclick="getInfo()" >submit</button>

<p id="label_id"></p>


<script type="text/javascript">

    function getInfo() {
        $.ajax({
            type: 'GET',
            url: 'Product?val=5',
            dataType: 'json',
            success: function (data) {
                //comment you will find email address from this data object.
                //bind data to view.

                $('#label_id').html(data.Description);
            }
        });
    }
</script>

bottom of page