.Net Core Web Api_笔记01

.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


<<:  Day01.从防疫特助到管道的故事谈Blue Prism

>>:  [Day 1] 前言-为甚麽要探索?

Day 15. 模板语法Template Syntax – 指令

前两天讲了模板语法中的插值,今天来讲指令的部分吧۹(ÒہÓ)۶ Directives 指令 Vue的...

机器学习:演算法

线性代数 LR:逻辑回归(Logistic Regression): 预测事件发生的机率(y=1)...

Day29 假设我们生活在别人的AR世界 那我们是不是很有可能明天就被删除了!?

上一篇说到了,AR宠物的部分,如果我们真的能用程序模拟出动物的习性、动作,那是不是代表说我们也能模拟...

【Day 30】递回

最後一天,我想要用递回(Recursion)来结束我们的三十天! 递回的观念,其实就是让一个函式可以...

Day-24 快速面试之考题大公开!(3)

听听其他人对於快速面试的应对。 有被问到专案的优化方式如何,当时我答不好(冏)後来听到组员回答的很...