Buscar contenidos

viernes, 6 de octubre de 2017

C# Método dinámico Verbo Post HttpClient WebAPIClient

Demo consumo WebAPI





Método WebAPI


    // POST api/values
        [HttpPost]
        public InfoPersonal Post(Persona persona)
        {
            InfoPersonal infoPersonal = new InfoPersonal()
            {
                personaId = persona.Id,
                celular = 123456,
                direccion="centro alajuela"
            };

            return infoPersonal;

  

Clase de Input Output de ejemplo


    public partial class Persona
    {
        public int Id { get; set; }
        public string Nombre { get; set; }
        public System.DateTime Nacimiento { get; set; }
        public int Edad { get; set; }
    }


    public class InfoPersonal
    {
        public int personaId { get; set; }
        public string direccion { get; set; }
        public int celular { get; set; }

    }

Clase para consumo de WebAPI



 public class WebAPIClientManager
    {
        string _baseAddress = "";

        public WebAPIClientManager(string baseAddress)
        {
            _baseAddress = baseAddress;
        }

        public TOutput VerbPost<TInput, TOutput>(string methodRouteURL, TInput modelInput, TOutput modelOuput)
        {
            using (System.Net.Http.HttpClient client = new HttpClient())
            {
                System.Uri baseUri = new Uri(_baseAddress);

                var requestUri = new Uri(baseUri, methodRouteURL);

                using (var requestWriter = new System.IO.StringWriter())
                {
                    var requestSerializer = JsonSerializer.Create();

                    requestSerializer.Serialize(requestWriter, modelInput);

                    var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json");

                    var responseMessage = client.PostAsync(requestUri, content).Result;

                    responseMessage.EnsureSuccessStatusCode();

                    var stream = responseMessage.Content.ReadAsStreamAsync().Result;

                    using (JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)))
                    {
                        var serializer = new JsonSerializer();

                        modelOuput = serializer.Deserialize<TOutput>(jsonReader);

                        return modelOuput;
                    }
                }

            }

        }

    }

No hay comentarios:

Publicar un comentario