สร้างโปรเจ็กส์แบบ Web API

  1. สร้างด้วย Command Line
  2. สร้างด้วย Visual Studio 2019
  3. ดูไฟล์ต่างๆในโปรเจ็กส์

1.สร้างด้วย Command Line

สร้างโปรเจ็กส์แบบ webapi ชื่อโปรเจ็กส์ WebApi

> dotnet new webapi -o WebApi

2.สร้างด้วย Visual Studio 2019

สร้างโปรเจ็กส์ใหม่ เลือก Create a new project

พิมพ์ ASP เลือกภาษา C#

เลือก ASP.NET Core Web Application

ตั้งชื่อโปรเจ็กส์ WebApi

เลือก template เป็น API และที่ด้านบนเลือกเป็น .NET Core และ ASP.NET Core 2.2

เสร็จแล้วกด Create

ลองรันดู จะรันได้ละ เช่นเรียก https://localhost:44387/api/values

แต่ถ้าเรียก https://localhost:44387/ จะ error 404

เรียกด้วย curl

curl -k -s https://localhost:44387/api/values

ถ้าใช้ Azure Cloud Shell ก็จัด format ของเอาท์พุท JSON ให้สวยด้วย jq

curl -k -s https://localhost:5001/api/values | jq

3.ดูไฟล์ต่างๆในโปรเจ็กส์

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Startup.cs – Configures services and the app’s HTTP request pipeline.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace WebApi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }
}

Program.cs – Contains a Main method—the app’s managed entry point.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace WebApi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
}

ValuesController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public ActionResult<string> Get(int id)
        {
            return "value";
        }

        // POST api/values
        [HttpPost]
        public void Post([FromBody] string value)
        {
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}