繁体   English   中英

如何将 JsonString 和 HttpPostedFileBase 图片发布到 Web 服务?

[英]How to POST a JsonString and a HttpPostedFileBase picture to a Web Service?

Json 字符串具有以下结构: {"CODIGO_AGENCIA":"HN001001","CODIGO_USUARIO":"some user","CODIGO_CATEGORIA":1}

这是 WS 要求的参数:

公共异步任务 SubirImagenCategoria(字符串 JsonString,HttpPostedFileBase 存档)

//这是我到目前为止得到的,web 服务返回 json 字符串为空的错误,我完全不知道如何继续。

public static async Task<CustomJsonResult> SubirImagenCategoría(int CodigoCategoria, HttpPostedFileBase Archivo)
    {
        usuario = UtilClass.GetUsuarioSesion();
        var modelo = new SUBIR_IMAGEN_CAT();
        modelo.CODIGO_AGENCIA = usuario.CodigoAgencia;
        modelo.CODIGO_USUARIO = usuario.Nombre;
        modelo.CODIGO_CATEGORIA = 1;

        CustomJsonResult result = new CustomJsonResult();
        try
        {
            var JsonString = JsonConvert.SerializeObject(modelo);

            var formContent = new MultipartFormDataContent("form-data");

            StringContent jsonPart = new StringContent(JsonString.ToString());
            jsonPart.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
            jsonPart.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            formContent.Add(jsonPart);


            /* byte[] Bytes = new byte[Archivo.InputStream.Length + 1];
             Archivo.InputStream.Read(Bytes, 0, Bytes.Length);
             var fileContent = new ByteArrayContent(Bytes);
             fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data") { FileName = Archivo.FileName };

             formContent.Add(fileContent);*/

            StreamContent filePart = new StreamContent(Archivo.InputStream);
            filePart.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
            filePart.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
            filePart.Headers.ContentDisposition.FileName = Archivo.FileName;

            formContent.Add(filePart);

            var test = formContent;

            /*HttpContent jsonParam = new StringContent(JsonString);
            HttpContent fileStream = new StreamContent(Archivo.InputStream);
            formData.Add(jsonParam, "JsonString", "JsonString");
            formData.Add(fileStream, "Archivo", "Archivo");*/

            /*var values = new Dictionary<string, string>
            {
                { "JsonString", ("{\"CODIGO_AGENCIA\":"+usuario.CodigoAgencia+",\"CODIGO_USUARIO\":\""+usuario.Nombre+"\" ,\"CODIGO_CATEGORIA\":\""+CodigoCategoria+"\"}") },

            };

            HttpContent myBody = new FormUrlEncodedContent(values);*/

            var formData = new MultipartFormDataContent();
            String url = DataEntityLayer.Database.Environment.getFinalUrl(Util.UtilWS.subirImagenesCategorias);

        
            var myHttpClient = new HttpClient();
            
            var response = await myHttpClient.PostAsync(url, formContent);
            string stringContent = await response.Content.ReadAsStringAsync();

            result = JsonConvert.DeserializeObject<CustomJsonResult>(stringContent);
        }
        catch (Exception ex)
        {
            result.Error = ex.Message;
        }
        return result;
    }

这就是我从 postman 测试 WS 的方式

经过多次尝试,几乎精神和情绪崩溃,它终于奏效了。 链接中的示例 3 对我有用。

public static UsuarioSesion usuario = new UsuarioSesion();
    public static async Task<CustomJsonResult> SubirImagenCategoría(int CodigoCategoria, HttpPostedFileBase Archivo)
    {
        usuario = UtilClass.GetUsuarioSesion();
        var modelo = new SUBIR_IMAGEN_CAT();
        modelo.CODIGO_AGENCIA = usuario.CodigoAgencia;
        modelo.CODIGO_USUARIO = usuario.Nombre;
        modelo.CODIGO_CATEGORIA = CodigoCategoria;

        CustomJsonResult result = new CustomJsonResult();
        try
        {
            var JsonString = JsonConvert.SerializeObject(modelo);

            var formContent = new MultipartFormDataContent();
           
            HttpContent JsonParam = new StringContent(JsonString);
            formContent.Add(JsonParam, "JsonString");

            var fileContent = new StreamContent(Archivo.InputStream);
            fileContent.Headers.Add("Content-Type", "application/octet-stream");
            fileContent.Headers.Add("Content-Disposition", "form-data; name=\"Archivo\"; filename=\"" + Archivo.FileName.ToString() + "\"");
            formContent.Add(fileContent, "file", Archivo.FileName.ToString());

         
            String url = DataEntityLayer.Database.Environment.getFinalUrl(Util.UtilWS.subirImagenesCategorias);
            var myHttpClient = new HttpClient();
            var response = await myHttpClient.PostAsync(url, formContent);
            string stringContent = await response.Content.ReadAsStringAsync();

            result = JsonConvert.DeserializeObject<CustomJsonResult>(stringContent);
        }
        catch (Exception ex)
        {
            result.Error = ex.Message;
        }
        return result;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM