public async Task Update(TModelo model) { // await: bloquea hasta que termine var datos = Serializacion <TModelo> .Serializar(model); using (var handler = new HttpClientHandler()) { // define la cabecera de auenticación if (auth) { handler.Credentials = new NetworkCredential(user, pass); } using (var client = new HttpClient(handler)) { var contenido = new StringContent(datos); // mi objeto serializado contenido.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var r = await client.PutAsync(new Uri(url), contenido); // no cierra hasta que termine if (!r.IsSuccessStatusCode) { throw new Exception("Fallo gordo"); } } } }
public async Task <TModelo> Add(TModelo model) { var datos = Serializacion <TModelo> .Serializar(model); using (var handler = new HttpClientHandler()) { if (auth) { handler.Credentials = new NetworkCredential(user, pass); } using (var client = new HttpClient(handler)) { var contenido = new StringContent(datos); contenido.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var r = await client.PostAsync(new Uri(url), contenido); if (!r.IsSuccessStatusCode) { throw new Exception("Fallo gordo"); } var objSerializado = await r.Content.ReadAsStringAsync(); return(Serializacion <TModelo> .Deserializar(objSerializado)); } } }
//aync firma que ponemos en el metodo para forzar a que sea un metodo asincrono //await esperar a que termine una operacion para lanzar otra ? public async Task Update(TModelo model) { var datos = Serializacion <TModelo> .Serializar(model); //HttpClientHandler se encarga de manejar las peticiones del HttpClient //cabeceras, autenticacion etc. using (var handler = new HttpClientHandler()) { if (auth) { handler.Credentials = new NetworkCredential(user, pass); } //HttpCliente crea un cliente nativo puro HTTP(como si abrieramos una especia de navegador web) using (var client = new HttpClient(handler)) { //StringContent le doy una cadena de texto plano y la prepara para enviarla en una peticion HTTP var contenido = new StringContent(datos); contenido.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var r = await client.PutAsync(new Uri(url), contenido); if (!r.IsSuccessStatusCode) { throw new Exception("Fallo al actualizar"); } } } }
//Hay que ponerlo como asincrono public async Task Update(TModelo model) { //Datos = objeto que le mando serializado var datos = Serializacion <TModelo> .Serializar(model); //HttpClient: Crea un cliente y se maneja atraves del Handler //Se encarga de autenticar(credenciales), crear las cabeceras... using (var handler = new HttpClientHandler()) { //En el handler se podria meter mas informacion if (auth) { handler.Credentials = new NetworkCredential(user, pass); } using (var client = new HttpClient(handler)) { var contenido = new StringContent(datos); contenido.Headers.ContentType = new MediaTypeHeaderValue("application/json"); //Si no le metemos el await nos aseguramos que no cierra el client hasta que nosotros se lo digamos. Ya que si lo cierra nos quedamos sin informacion asi que es mejor ponerlo. //El putAsync devuelve un task //Si no le haces un await se le podria meter un callback --> .ContinueWith //client.PutAsync(new Uri(url), contenido).ContinueWith(...); var r = await client.PutAsync(new Uri(url), contenido); if (!r.IsSuccessStatusCode) { throw new Exception("Fallo gordo"); } } } }
public async Task Update(TModel model) { var datos = Serializacion <TModel> .Serializar(model); //se crea el HttpClientHandler para poder añadir credenciales de autenticacion using (var handler = new HttpClientHandler()) { if (auth) { handler.Credentials = new NetworkCredential(user, pass); } using (var client = new HttpClient(handler)) { var contenido = new StringContent(datos); contenido.Headers.ContentType = new MediaTypeHeaderValue("application/json"); //el await es para que se espere a ejecutar var r = await client.PutAsync(new Uri(url), contenido); if (!r.IsSuccessStatusCode) { throw new Exception("Fail on update"); } } } }
//Para que un metodo sea asincrono hay que marcarlo como Task y async //Para esperar y poder utilizar lo que devuelve una llamada asincrona //se usa await public async Task Update(TModelo model) { var datos = Serializacion <TModelo> .Serializar(model); //No se usa webrequest porque puede/suele fallar en los metodos post/put/delete //Se usa el httppclienthandler en su lugar. using (var handler = new HttpClientHandler()) { if (auth) { handler.Credentials = new NetworkCredential(user, pass); } //Crea un client pasandole la información del handler(que tiene los datos de autenticacion) using (var client = new HttpClient(handler)) { //stringcontent manipula una cadena de texto plano para que la pueda interpretar //una cabecera http var contenido = new StringContent(datos); //indicas en la cabecera el tipo de contenido que tiene. contenido.Headers.ContentType = new MediaTypeHeaderValue("application/json"); //le indicas q espere(await) para que no se cierre la conexión del using //mientras está haciendo el put var respuesta = await client.PutAsync(new Uri(url), contenido); if (!respuesta.IsSuccessStatusCode) { throw new Exception("Error al modificar"); } } } }
public async Task <TModelo> Add(TModelo model) { var datos = Serializacion <TModelo> .Serializar(model); using (var handler = new HttpClientHandler()) { if (auth) { handler.Credentials = new NetworkCredential(user, pass); } using (var client = new HttpClient(handler)) { var contenido = new StringContent(datos); contenido.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var r = await client.PostAsync(new Uri(url), contenido); // poniendo el await nos aseguramos que no se cierra la conexion hasta que se haya mandado el contenido. if (!r.IsSuccessStatusCode) { throw new Exception("Puta mierda"); } var objSerializado = await r.Content.ReadAsStringAsync(); return(Serializacion <TModelo> .Deserializar(objSerializado)); } } }