iT邦幫忙

2021 iThome 鐵人賽

DAY 1
2
自我挑戰組

.NET Core WebApi網頁應用開發系列 第 1

.Net Core Web Api_筆記01

  • 分享至 

  • xImage
  •  

.net core web api
可以和任何前端Client端技術或框架(javascript , jQuery , Vue , React , Angular)做結合
藉由URL請求來實現資料添加、更新、刪除以及查詢等操作
甚至跟其他程式語言(PHP , Node.Js)交換溝通因為都是透過HTTP在做交流
https://ithelp.ithome.com.tw/upload/images/20210901/20107452tICJWRLZfe.png

https://ithelp.ithome.com.tw/upload/images/20210901/20107452gP1Ff7L2yS.png

https://ithelp.ithome.com.tw/upload/images/20210901/20107452wrRcs9ELD6.png

啟用OPEN API可以暫時勾消

新創建出來的專案
可以觀察到只會有Controllers文件夾
不像MVC會再多出Models , Views
https://ithelp.ithome.com.tw/upload/images/20210901/20107452moaRGpKS8n.png

https://ithelp.ithome.com.tw/upload/images/20210901/20107452g1jjTXsRcp.png

啟動預設範例執行結果
https://ithelp.ithome.com.tw/upload/images/20210901/20107452xoBdq1Lzs5.png

因為web api 不需要View視圖(也無法回傳view)
僅作資料回傳

預設範本的WeatherForecastController.cs
code部分

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

namespace MyApiTest1.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}

有使用[ApiController] attribute修飾
代表該Controller為api 控制器

而在Program.cs中的Main()跟.net core mvc一樣程式進入點

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

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

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

主要用於web api應用初始化時候要做的配置

在Startup.cs 啟動class程式文件中

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

namespace MyApiTest1
{
    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.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

基本上跟MVC沒有太大差異同樣也是在ConfigureServices方法中將服務注入
這裡別於MVC僅注入Controllers服務而已

在.NET Core MVC中的ConfigureServices

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
}

在.NET Core WebAPI中的ConfigureServices

public void ConfigureServices(IServiceCollection services)
{

    services.AddControllers();
}

本篇同步發表至個人blog
https://coolmandiary.blogspot.com/2021/07/net-core-web-api01.html


下一篇
.Net Core Web Api_筆記02_HTTP資源操作模式GET
系列文
.NET Core WebApi網頁應用開發25
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
jumpbow
iT邦新手 4 級 ‧ 2021-12-27 10:56:40

圖片都不見了/images/emoticon/emoticon06.gif

Samuel iT邦好手 1 級 ‧ 2021-12-27 11:01:00 檢舉

那裡的圖片??

我要留言

立即登入留言