Beispiel #1
0
        public async Task <ResponseCategoriaSubirImagenDtoApi> SubirImagen(RequestCategoriaModificarImagenMetodo1DtoApi prm)
        {
            ResponseCategoriaSubirImagenDtoApi resultado = new ResponseCategoriaSubirImagenDtoApi();
            int statusCode = 0;

            try
            {
                //Dentro de AJAX => datatype: 'json', headers: {'Authorization': 'Basic ' + valor token }, ....
                var    response = string.Empty;
                string url      = string.Format("{0}{1}/ImagenMetodo1", ConstanteVo.UrlBaseApi, _nombreControlador);

                using (var client = new HttpClient())
                {
                    if (ConstanteVo.ActivarLLamadasConToken && !string.IsNullOrEmpty(ConfiguracionToken.ConfigToken))
                    {
                        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", ConfiguracionToken.ConfigToken.Trim());
                    }

                    var content = new StringContent(JsonConvert.SerializeObject(prm), Encoding.UTF8, "application/json");
                    HttpResponseMessage result = await client.PostAsync(new Uri(url), content);

                    if (result != null)
                    {
                        response = await result.Content.ReadAsStringAsync();

                        statusCode = (int)result.StatusCode;
                    }
                }

                resultado = JsonConvert.DeserializeObject <ResponseCategoriaSubirImagenDtoApi>(response);
            }
            catch (Exception ex)
            {
                resultado.ListaError.Add(new ErrorDtoApi
                {
                    Mensaje = (ex.InnerException == null ? ex.Message : ex.InnerException.Message).Replace(Environment.NewLine, " ")
                });
            }
            finally
            {
                if (resultado != null)
                {
                    resultado.StatusCode = statusCode;
                }
            }

            return(resultado);
        }
Beispiel #2
0
        public ActionResult SubirImagenes(IFormFile file)
        {
            string urlImagenNueva = string.Empty;
            ResponseCategoriaSubirImagenDtoApi respuesta = new ResponseCategoriaSubirImagenDtoApi();

            try
            {
                if (file == null)
                {
                    respuesta.ListaError.Add(new ErrorDtoApi {
                        Mensaje = "El archivo no ha sido cargado"
                    });
                    return(BadRequest(respuesta));
                }
                string idCategoria = string.Empty;
                try
                {
                    idCategoria = Request.Form["IdCategoria"][0];
                }
                catch
                {
                    respuesta.ListaError.Add(new ErrorDtoApi {
                        Mensaje = "El IdCategoria no ha sido cargado"
                    });
                    return(BadRequest(respuesta));
                }

                if (file.Length == 0)
                {
                    respuesta.ListaError.Add(new ErrorDtoApi {
                        Mensaje = "El archivo no ha sido cargado"
                    });
                    return(BadRequest(respuesta));
                }

                bool esError = false;
                if (idCategoria == null)
                {
                    esError = true;
                }
                if (idCategoria == "0")
                {
                    esError = true;
                }
                if (Request.Form.Files == null)
                {
                    esError = true;
                }
                if (!Entidad.Utilitario.Util.EsInt(idCategoria))
                {
                    esError = true;
                }

                if (!esError)
                {
                    var    nombreArchivo = System.Net.Http.Headers.ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                    string extension     = Path.GetExtension(nombreArchivo).Trim().Replace(".", string.Empty).ToLower();
                    byte[] archivoBytes;
                    using (var memoryStream = new MemoryStream())
                    {
                        file.CopyTo(memoryStream);
                        archivoBytes = memoryStream.ToArray();
                    }

                    if (archivoBytes != null)
                    {
                        RequestCategoriaModificarImagenMetodo1DtoApi prmApi = new RequestCategoriaModificarImagenMetodo1DtoApi
                        {
                            IdCategoria       = Convert.ToInt32(idCategoria),
                            ExtensionSinPunto = extension,
                            ArchivoBytes      = archivoBytes
                        };

                        var t = Task.Run(() => _lnCategoria.SubirImagen(prmApi));
                        t.Wait();
                        if (t.Result != null)
                        {
                            respuesta = t.Result;
                        }
                    }
                }
                else
                {
                    //Error en los parametros
                    respuesta.ListaError.Add(new ErrorDtoApi {
                        Mensaje = "Parametros incompletos para continuar con el proceso"
                    });
                    return(BadRequest(respuesta));
                }
            }
            catch (InvalidOperationException invEx)
            {
                string mensajeInvEx = (string.IsNullOrEmpty(invEx.StackTrace) ? invEx.Message : invEx.StackTrace).Replace(Environment.NewLine, " ");
                Logger.Log(Logger.Level.Error, mensajeInvEx);
                respuesta.ListaError.Add(new ErrorDtoApi {
                    Mensaje = string.Format("[InvalidOperationException]{0}", mensajeInvEx)
                });
                return(BadRequest(respuesta));
            }
            catch (Exception ex)
            {
                string mensajeEx = (ex.InnerException == null ? ex.Message : ex.InnerException.Message).Replace(Environment.NewLine, " ");
                Logger.Log(Logger.Level.Error, mensajeEx);
                respuesta.ListaError.Add(new ErrorDtoApi {
                    Mensaje = string.Format("[Exception]{0}", mensajeEx)
                });
                return(BadRequest(respuesta));
            }

            return(Ok(respuesta));
        }