Part 2 - Editing Data
In part 1, we setup a basic service using ASP.NET where we had a couple of cats making cat sounds. That's fine for one or two cats, but what if we want to have a horde of cats?
Let's start by making a new controller called HordeController.cs (the same way we did in the other blog post); then, remember to add using Microsoft.AspNetCore.Mvc
library to the top.
Now inside of that controller, let's make an Add
and Get
method. The "add" will add a cat, the "get" will get the cat's value.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;namespace MeowWorld.Controllers
{
public class HordeController : Controller
{
private Dictionary<string, string> _Cats = new Dictionary<string, string>();[HttpGet("horde/add/{cat}")]
public string Add(string cat, string sound)
{
_Cats[cat] = sound;return String.Format("{0} added to the horde!", cat);
}[HttpGet("horde/{cat}")]
public string Get(string cat)
{
if(!_Cats.ContainsKey(cat))
{
return "Cat not found.";
}
return _Cats[cat];
}
}
}
Now if you run this code, you can go to .../horde/add/paul?sound=Hiss.
to add Paul.
Note: It's often better to use the post method instead of the get method for sending data. Get is being used in this tutorial for ease of access through the browser.
Now that Paul has been added, we can head over to ../horde/paul
and find ... nothing. Paul doesn't exist.
What happened? Where's Paul?!
Paul was disposed of by the garbage collector as soon as the page finished loading. This is because Paul was being stored in an instance variable. Each request generates a new instance of the HordeController, so the old data is not accessible.
We can easily fix this by making _Cats
a static class variable.
private static Dictionary<string, string> _Cats = new Dictionary<string, string>();
Now when we add Paul, he'll stay in the horde.
Note: In a real-world situation, you'll probably want to store the cats in an actual database instead of a static dictionary.
Now that we have a way of adding Paul, we should also add a way of editing the sound he makes.
CRUD (Create, Read, Update, Delete)
There are several ways of doing API's such as REST and SOAP, but this is an introductory tutorial so we're going to keep things simple with a REST-like API.
There's a variety of HTTP Methods we can use to connect to a web service. I already told you about Get, but there is also Delete, Patch, Post, Put, and others.
If we want to update what the cat says, we can make a method that runs an HTTP Update. This method is similar to the one for adding a cat.
[HttpPatch("horde/{cat}")]
public string Patch(string cat, string sound)
{
if (!_Cats.ContainsKey(cat))
{
return "Cat not found.";
}_Cats[cat] = sound;
return "Cat updated.";
}
We can also add a method for removing a cat from the horde (although I'm not sure why you'd want to do that). This one looks similar to the Get method, but instead of returning a cat, it gets rid of it.
[HttpDelete("horde/{cat}")]
public string Delete(string cat)
{
if (!_Cats.ContainsKey(cat))
{
return "Cat not found.";
}_Cats.Remove(cat);
return "Cat deleted.";
}
Now to start the server and test these.
Postman
There are many tools you can use for testing API calls. In general, they are all pretty similar, so by learning one you should be able to learn others as well. In this tutorial, we'll be using a program called Postman, which can be installed on Linux, Mac, or Windows, or as a plugin for Chrome.
You can install it here:
http://getpostman.com/apps
Once you have Postman up and running...
Add Paul to the horde again.
Now if we want to edit what Paul says, select PATCH
from the drop down and enter .../horde/paul?sound=Mew.
in the request URL. Click Send
to update the data. Now when you get Paul's sound, it should say Mew.
You can also remove Paul from the horde by selecting DELETE
from the drop down and enter .../horde/paul
in the request URL. Click Send
and say goodbye to Paul.
Content Body
In practice, you should be sending the sound as body content, not as a query string, so let's quickly fix that in the code.
Change the Add method to:
[HttpPost("horde/{cat}")]
public string Post(string cat, [FromBody]string sound)
{
_Cats[cat] = sound;
return String.Format("{0} added to the horde!", cat);
}
Now in order to add a cat:
* Set the HTTP Method to Post
* Set the URL to .../horde/paul
* In the Body select raw
* In the Body select JSON (application.json)
from the drop down
* In the Body write "Hiss."
Alternatively, you can select form-data
and set the key
to sound and value
to Hiss.
Send the call and it should add Paul.
Now for Patch
all you need to do is add [FromBody]
to tell the code that value is coming from the content body.
[HttpPatch("horde/{cat}")]
public string Patch(string cat, [FromBody]string sound)
{
if (!_Cats.ContainsKey(cat))
{
return "Cat not found.";
}_Cats[cat] = sound;
return "Cat updated.";
}
Now you can change "Hiss."
to something else (make sure you keep the quotes) and use PATCH
instead of POST
as the send method to update it.
Now you can either do a GET
request to the same URL or point your browser at .../horde/paul
to see what they have to say.
Conclusion
Now you know how to get a basic API up and running with data manipulation. Next, we'll show you how to get it working on OpenShift.
Sobre el autor
Más similar
Navegar por canal
Automatización
Las últimas novedades en la automatización de la TI para los equipos, la tecnología y los entornos
Inteligencia artificial
Descubra las actualizaciones en las plataformas que permiten a los clientes ejecutar cargas de trabajo de inteligecia artificial en cualquier lugar
Nube híbrida abierta
Vea como construimos un futuro flexible con la nube híbrida
Seguridad
Vea las últimas novedades sobre cómo reducimos los riesgos en entornos y tecnologías
Edge computing
Conozca las actualizaciones en las plataformas que simplifican las operaciones en el edge
Infraestructura
Vea las últimas novedades sobre la plataforma Linux empresarial líder en el mundo
Aplicaciones
Conozca nuestras soluciones para abordar los desafíos más complejos de las aplicaciones
Programas originales
Vea historias divertidas de creadores y líderes en tecnología empresarial
Productos
- Red Hat Enterprise Linux
- Red Hat OpenShift
- Red Hat Ansible Automation Platform
- Servicios de nube
- Ver todos los productos
Herramientas
- Training y Certificación
- Mi cuenta
- Soporte al cliente
- Recursos para desarrolladores
- Busque un partner
- Red Hat Ecosystem Catalog
- Calculador de valor Red Hat
- Documentación
Realice pruebas, compras y ventas
Comunicarse
- Comuníquese con la oficina de ventas
- Comuníquese con el servicio al cliente
- Comuníquese con Red Hat Training
- Redes sociales
Acerca de Red Hat
Somos el proveedor líder a nivel mundial de soluciones empresariales de código abierto, incluyendo Linux, cloud, contenedores y Kubernetes. Ofrecemos soluciones reforzadas, las cuales permiten que las empresas trabajen en distintas plataformas y entornos con facilidad, desde el centro de datos principal hasta el extremo de la red.
Seleccionar idioma
Red Hat legal and privacy links
- Acerca de Red Hat
- Oportunidades de empleo
- Eventos
- Sedes
- Póngase en contacto con Red Hat
- Blog de Red Hat
- Diversidad, igualdad e inclusión
- Cool Stuff Store
- Red Hat Summit