Lo que pretende es mostrar como podemos enviar y recibir un archivo a una Api utilizando RestSharp o HttpClient
Código API
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public async Task<HttpResponseMessage> Post() { try { byte[] documento = await Request.Content.ReadAsByteArrayAsync(); return await Task.Run<HttpResponseMessage>(() => ObtenerDocumento.DocumentoPdf(documento)); } catch (Exception ex) { return Request.CreateResponse(HttpStatusCode.BadRequest, new ErrorModel() { Codigo = ex.HResult.ToString(), Error = ex.Message }); } } |
Cliente usando RestSharp para cualquier Framework
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public static byte[] FirmarPdf(byte[] contenido) { var client = new RestClient("http://urlAPI"); client.Authenticator = new HttpBasicAuthenticator("usuario", "clave"); var request = new RestRequest("api/FirmaPdf/", Method.POST); request.AddParameter("application/pdf", contenido, ParameterType.RequestBody); var result= client.Execute(request); var document = result.RawBytes; return document; } |
Cliente usando HttpClient a partir del FrameWork 4.5
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
public static HttpClient client { get { var http = new HttpClient(); http.BaseAddress = new Uri(URL_API); http.DefaultRequestHeaders.Accept.Clear(); http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic" , EncodeTo64(string.Format("{0}:{1}", USER, PASS))); return http; } } [TestMethod] public async Task TestPost() { var path = RUTA_LOCAL + "documento.pdf"; var data = File.ReadAllBytes(path); ByteArrayContent byteContent = new ByteArrayContent(data); var respuesta =await client.PostAsync("api/Funcion/",byteContent); var documento=await respuesta.Content.ReadAsByteArrayAsync(); File.WriteAllBytes(RUTA_LOCAL+"nuevo.pdf", documento); Assert.AreEqual(true, respuesta.IsSuccessStatusCode); } |