피드 구독

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.


저자 소개

채널별 검색

automation icon

오토메이션

기술, 팀, 인프라를 위한 IT 자동화 최신 동향

AI icon

인공지능

고객이 어디서나 AI 워크로드를 실행할 수 있도록 지원하는 플랫폼 업데이트

open hybrid cloud icon

오픈 하이브리드 클라우드

하이브리드 클라우드로 더욱 유연한 미래를 구축하는 방법을 알아보세요

security icon

보안

환경과 기술 전반에 걸쳐 리스크를 감소하는 방법에 대한 최신 정보

edge icon

엣지 컴퓨팅

엣지에서의 운영을 단순화하는 플랫폼 업데이트

Infrastructure icon

인프라

세계적으로 인정받은 기업용 Linux 플랫폼에 대한 최신 정보

application development icon

애플리케이션

복잡한 애플리케이션에 대한 솔루션 더 보기

Original series icon

오리지널 쇼

엔터프라이즈 기술 분야의 제작자와 리더가 전하는 흥미로운 스토리