.Net Core Web Api_笔记04_HTTP资源操作模式Put

基本上跟POST是有点类似的作法
通常用於资料更新(所以资料必须是已存在於目前db的)

新增额外的action method for更新

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

namespace MyApiTest1.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TeacherController : ControllerBase
    {
        [HttpPost("Add")]
        public string AddPerson(Person person)
        {
            int id = person.Id;
            string name = person.Name;
            int age = person.Age;
            string sex = person.Sex;
            return "完成添加";
        }

        [HttpPut("Update")]
        public string UpdatePerson(Person person)
        {
            int id = person.Id;
            string name = person.Name;
            int age = person.Age;
            string sex = person.Sex;
            return "完成更新";
        }

    }
}

然後在额外新增一html档案用於更新教师资讯的测试页面
UpdateTeacher.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Update Teacher Info</title>
    <script src="jquery/jquery.min.js"></script>
</head>
<body>
    <div>
        <input type="button" id="btnUpdate" value="更新" />
        <span id="msg"></span>
    </div>

    <script type="text/javascript">
        $("#btnUpdate").click(function () {
            $.ajax({
                //请求模式
                type: "put",
                //请求的URL
                url: "api/Teacher/Update",
                //预期server responde的资料型态
                dataType: "text",
                //请求送出发送的资料(body内文json字串)
                data: JSON.stringify({ id: 1, name: 'Andy', age: 22, sex: 'man' }),
                //内文型态
                contentType: "application/json",
                success: function (result) {
                    $("#msg").text(result);
                }
            });
        });
    </script>
</body>
</html>

基本上跟POST使用没有太大落差只在於type调整
运行效果
https://ithelp.ithome.com.tw/upload/images/20210905/20107452LeaOibEyj8.png

以上就是本次介绍的HttpPut操作测试模拟

本文也已同步发表到个人部落格
https://coolmandiary.blogspot.com/2021/09/net-core-web-api04httpput.html


<<:  .NET Core第5天_IWebHostEnvironment 的用途是舍麽?

>>:  (Day5) 原始型别及物件型别

DAY3 MongoDB 连线与 IDE

DAY3 MongoDB 连线与 IDE MongoDB 的连线方式主要有三种,分别是: legac...

[Day05] Web API 专案架构

今天我们来介绍一下我们 API 专案的架构。.NET 帮我们产生的专案包含以下几个部分: Prope...

Vuex 是什麽

Vuex 是 Vue 提供的一种资料状态管理的模式,它可以统一控管资料的状态,都是在小型的 SPA ...

仿Trello - 前端 Apollo Client 串接 GraphQL API

本系列文以制作专案为主轴,纪录小弟学习React以及GrahQL的过程。主要是记下重点步骤以及我觉...

Day 5 | 游戏流程与关卡设定

今天要为各位介绍我们的游戏流程与关卡设定 游戏流程 上图是游戏的流程图,我们的游戏采单一故事线的剧情...