上一篇介绍到GET主要用於资料获取
HttpPost主要用於资料添加
这里我们沿用之前专案新增一个TeacherController.cs
并增加一个Add的方法用HttpPost属性修饰
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 "完成添加";
}
}
}
这里没有涉及DB只是模拟资料传进来後打印添加完成的显示文
写完了之後当然要来尝试呼叫看看感受POST的功能
POST无法直接用网址访问方式来测试呼叫
因此这里我们使用jQuery来简单测试基本api呼叫
预设专案不支援一些静态文件资源存取(比方html,js,图片)。
因此需要至Startup.cs中
在Configure 方法
利用middleware(中介软件)来启用静态资源
app.UseStaticFiles();//启用静态资源可存取性使其可以访问wwwroot目录下的静态资源
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();//启用静态资源可存取性
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
在此还要特别注意
中介软件顺序
写成是顺序要特别留意
比方Authentication一定要在Authorization之上。
新增完该middleware後
再到专案下新增wwwroot目录(会自动变地球图示)
之後再新增AddTeacher.html
再补加上jQUery
透过新增用户端程序库新增
点选安装後就可以看到透过libman.json安装好的jQUery套件
我们直接在html中引入然後撰写提交POST请求的前端表单页面和相应jQuery处里逻辑
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Add Teacher Info</title>
<script src="jquery/jquery.min.js"></script>
</head>
<body>
<div>
<input type="button" id="btnAdd" value="添加" />
<span id="msg"></span>
</div>
<script type="text/javascript">
$("#btnAdd").click(function () {
$.ajax({
//请求模式
type: "post",
//请求的URL
url: "api/Teacher/Add",
//预期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>
实际呼叫测试
以上就是透过jQuery针对POST请求.net core web api的分享
已同步发表至个人部落格
https://coolmandiary.blogspot.com/2021/09/net-core-web-api03httppost.html
<<: Day 4. Hashicorp Nomad: resources
>>: .NET Core第4天_middleware是舍麽?
什麽是云端服务 ? 云端服务指的就是将软硬体等资源,放到网际网路上作为服务,使用者只需透过网路,就可...
"软件开发和盖教堂一样,当完成之後,我们就开始祈祷" - Sam Redwine...
听音乐先~ Rails操作实体 接续前一篇文章,做出一个实体後。 专案中 project_name/...
上一篇文章我们成功在Visual Studio里新增了Echo Bot的专案 也成功在Bot Fra...
环境 Windows 10 21H1 x64dbg Aug 2 2020, 13:56:14 Vis...