Create a webapi

Prerequisite

See Compile Aspnet core 1.1 outside Docker container but run within

Create a controller

Create a file TodoController.cs file in the same folder as HomeController.cs file. In a real application we should probably put it in a folder “api” or similar.

Fill it with the text below (which is a refinement of https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api ):

[Update:There is now a

1
dotnet new -t webapi

or similar so you don’t have to copypaste the code below. I plan to write about it as soon as I can.]

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication.Controllers
{
    // Setting the Route attribute is important.
    // Otherwise we don't get the restish behaviour we're looking for.
    // I cannot say exactly why this is so.
    [Route("api/[controller]")]
    public class TodoController : Controller
    {
        private static List _data =
        new List{
            new Item{
                Id = 1,
                Name = "One"
            },
            new Item{
                Id = 2,
                Name = "Two"
            },
        };
        [HttpGet]
        public IEnumerable<item> GetAll()
        {
            return _data;
        }
        [HttpGet("{id}", Name = "GetTodo")]
        public string Get(int id)
        {
            return _data.Single(d => d.Id == id).Name;
        }
        [HttpPut("{id}")]
        public IActionResult Put(int id, [FromBody] string name)
        {
            GetItem(id).Name = name;
            return new NoContentResult();
        }
        [HttpPost]
        public IActionResult Post(string name)
        {
            var item = new Item { Id = _data.Count() + 1, Name = name };
            _data.Add(item);
            return CreatedAtRoute("GetTodo", new { id = item.Id }, item);
        }
        private Item GetItem(int id)
        {
            return _data.Single(d => d.Id == id);
        }
    }
    public class Item
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}
</item>

Compile:

1
dotnet build

And start the web server with the application:

1
dotnet bin/Debug/netcoreapp1.1/MyWs.dll

Call the controller

Start another terminal.

First check what we have.

1
curl localhost:5000/api/Todo

Then check one item.

1
curl localhost:5000/api/Todo/2

Create a new.

1
2
curl --data "Name=Three" localhost:5000/api/Todo/
curl localhost:5000/api/Todo/3

Update an existing according to Stack overflow.

1
2
3
4
5
curl -H "Content-Type: application/json" \
-X PUT \
--data '"Tva"' \
localhost:5000/api/todo/2
curl localhost:5000/api/Todo/2

Tags: ,

Leave a Reply