.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操作測試模擬

留言

這個網誌中的熱門文章

經得起原始碼資安弱點掃描的程式設計習慣培養(五)_Missing HSTS Header

經得起原始碼資安弱點掃描的程式設計習慣培養(三)_7.Cross Site Scripting(XSS)_Stored XSS_Reflected XSS All Clients

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題