今天接續上一篇 .Net6 關於
Web API 的二三事 – form 直接 POST 到 Web API ,這次來筆記一下有關於怎麼使用 只用 Javascript 呼叫
Web API 。

注意不要忘記在 Program.cs 中加入 ,非常常忘記
//use Web API
app.MapControllers();
1. 第一個範例,透過 Javascript 進行 form submit
HTML Code:
<div style="margin-top:50px">
<h2>測試 純用 JS 呼叫 WebAPI </h2>
<form method="post" id="formMain">
<div style="margin-bottom:20px">
<legend>用戶帳號</legend><br />
<input class="input" type="text" placeholder="donma" name="userId">
</div>
<fieldset>
<legend>選擇你的興趣:</legend>
<div>
<input type="checkbox" name="hobby" checked value="釣魚">
<label>釣魚</label>
</div>
<div>
<input type="checkbox" name="hobby" checked value="睡覺">
<label>睡覺</label>
</div>
<div>
<input type="checkbox" name="hobby" value="看電影">
<label>看電影</label>
</div>
<div>
<input type="checkbox" name="hobby" value="上網">
<label>上網</label>
</div>
</fieldset>
<div>
<legend for="gender">性別</legend><br>
<select name="gender">
<option value="0">Female</option>
<option value="1">Male</option>
</select>
</div>
<div>
<legend for="">生日</legend><br>
<input class="input" type="date" placeholder="2022-10-11" value="2022-10-11" name="userBirth">
</div>
<div>
<legend for="">薪水</legend><br>
<input class="input" type="number" value="199.99" name="userSalary">
</div>
<hr />
<div>
<input type="submit" value="送出" id="btnSubmit">
</div>
</form>
<hr />
<div style="color:red">
<h3>
Result:
</h3>
<span id="spanResult"></span>
</div>
</div>
Web API C# Code :
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Dynamic;
namespace TestWebAPI1.API
{
[Route("api/test")]
[ApiController]
public class TestController : ControllerBase
{
[HttpGet]
public string Get()
{
return "Test Service";
}
[HttpPost]
[Route("sample2")]
public IActionResult RegistUserActionResult([FromForm] string userId,
[FromForm] string gender,
[FromForm] string[] hobby,
[FromForm] DateTimeOffset userBirth,
[FromForm] decimal? userSalary)
{
dynamic res = new ExpandoObject();
res.UserId = userId;
res.Gender = gender;
res.Hobby = hobby;
res.Birth = userBirth;
res.Salary = userSalary;
return Ok(res);
}
}
}
Javascript Code:
document.getElementById('formMain').addEventListener('submit', async function(event) {
event.preventDefault();
const formData = new FormData(this);
let response;
try {
let res = await fetch("/api/test/sample2", {
method: 'POST',
body: formData,
});
response = await res.json();
} catch (e) {
console.error("Request to server failed", e);
throw e;
}
document.getElementById("spanResult").innerHTML = JSON.stringify(response);
console.log("Response Object", JSON.stringify(response));
console.log("Read Object:" + response.UserId)
});
其實只是取代透過直接 html 的 sbumit,為何要這樣做呢,因為有時候你必須要在 submit 前做一些驗證,或是加資料後在往後送到 Web API
2. 第二個案例,自己在前端的一個物件透過 JSON 傳遞到 後段的 Web API,這邊案例我在後端是設計一個 叫做 User 的物件
前端傳遞過來一個 User 的物件,我在 Web API 小改變一些資訊後往前送。
User.cs :
public class User
{
public string Id { get; set; }
public string Name { get; set; }
public string[]? Hobby { get; set; }
public string Gender { get; set; }
public decimal? Salary { get; set; }
public DateTimeOffset Birth { get; set; }
}
Web API C# Code :
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Dynamic;
namespace TestWebAPI1.API
{
[Route("api/test")]
[ApiController]
public class TestController : ControllerBase
{
[HttpGet]
public string Get()
{
return "Test Service";
}
[HttpPost]
[Route("sample4")]
// 這邊記得要使用 frombody 不是 fromform
public IActionResult RegistUserActionJSONResult([FromBody] Models.User u)
{
dynamic res = new ExpandoObject();
u.Id += "_ServerEdited";
u.Hobby= u.Hobby.Concat(new string[] { "釣蝦" }).ToArray();
return Ok(u);
}
}
}
Javascript Code:
document.getElementById('formMain').addEventListener('submit', async function(event) {
event.preventDefault();
var requestData = new Object();
requestData.Id = "USERID";
requestData.Name = "Donma";
requestData.Hobby = ['睡覺','看電影'];
requestData.Gender = "1";
requestData.Salary = 199.999;
requestData.Birth = new Date();
let response;
try {
let res = await fetch("/api/test/sample4", {
method: 'POST',
body: JSON.stringify(requestData),
headers: {
'content-type': 'application/json'
}
});
response = await res.json();
} catch (e) {
console.error("Request to server failed", e);
throw e;
}
document.getElementById("spanResult").innerHTML = JSON.stringify(response);
console.log("Response Object", JSON.stringify(response));
});

基本上,你會遇到你設計的 物件屬性首字原本大寫,但是輸出會變成小寫,這時候需要再 Program.cs 加入

中間通訊:

今天先筆記到這邊,之後有啥怕忘記的我會再補上