.NetCore WebApi 學習 -- 控制器結構及前端訪問方式
控制器
//訪問的地址api/控制器名稱/方法名稱;action一般會省略
[Route("api/[controller]/[action]")]
public class TestController : ControllerBase
{
//[Route]與[HttpPost]內都設置了參數相當於這個方法有兩個請求地址
//兩個地址都是接在類上定義的地址后面使用
[Route("insert/{參數1}")]//{}大括號內為自定義參數,也可以只設置常量作為訪問地址
[HttpPost("insert/{參數1}")]
//地址上設置了參數后直接在地址后增加需要傳遞參數即可,否則需要另外傳遞接口所需要的參數
public async Task<ActionResult<Md5Test>> PostMd5Test(string 參數1,Md5Test md5Test)
{
//將傳來的數據進行處理
_context.Md5Test.Add(md5Test);
await _context.SaveChangesAsync();
return CreatedAtAction("GetMd5Test", new { id = md5Test.Id }, md5Test);//返回數據給客戶端
}
[HttpGet("Count")]
public PageModels GetPageContent()
{
int Md5TestsCount = _context.Md5Test1.Count();
PageModel.TableCount = Md5TestsCount;
PageModel.PageCount = (int)Math.Ceiling((double)Md5TestsCount / 20);
return PageModel;
}
[HttpGet("Page/{PageIndex}")]
public async Task<ActionResult<IEnumerable<Md5Test1>>> GetMd5TestPage(int PageIndex = 0)
{
return await _context.Md5Test1.Skip(PageIndex * PageModel.PageSize).Take(PageModel.PageSize).ToListAsync();
}
}
前端訪問方式
使用Ajax訪問
const item = {
Key: "AAAAAA",
Value: "36d04a9d74392c727b1a9bf97a7bcbac"
};
$.ajax({
url: 'api/Test/GetModel',
type:"get",
data: { Id: 1},
success: function(a) {
console.log(a);
}
});
$.ajax({
url: 'api/Test/GetModel/1',
type:"get",
success: function(a) {
console.log(a);
}
});
$.ajax({
url: 'api/Md5Test/insert',
type: "POST",
async: true,
dataType: "json",
data: item,
contentType: "application/x-www-form-urlencoded",
success: function(a) {
console.log(a);
}
});
使用fetch訪問
//fetch是一種HTTP數據請求的方式,是XMLHttpRequest的一種替代方案。
//fetch不是ajax的進一步封裝,而是原生js。
//fetch函數就是原生js,沒有使用XMLHttpRequest對象。
const item = {
Key: "AAAAAA",
Value: "36d04a9d74392c727b1a9bf97a7bcbac"
};
var url = `api/Test/insert/${參數}`;//請求地址為api/控制器名稱/定義的標識/參數;具體視自身定義內容而定
//var postReq = new Request(url, {method: 'POST'});//fetch跟隨的括號內的內容可以使用Request參數化
fetch(url, {
method: 'POST',//指定 POST HTTP 操作
headers: {//HTTP 請求標頭,分別指定接收和發送的媒體類型,此處將兩個標頭都設置為 application/json
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(item)//指定請求正文的 JSON 表示形式//json格式發送接口所需要的數據
})
.then(response => response.json())//接口訪問失敗時執行
.then(response => {
Page = response.data;//接口返回成功時執行//返回內容都在response.data中
})
.catch(error => console.error('Unable to add item.', error));//接口訪問出錯時執行
fetch(`${uri}/Count`)
.then(response => response.json())
.then(function (date1) {
--返回內容在date1中,可在此處處理
})
.catch(error => console.error('Unable to get items.', error));
使用VUE-axios訪問
VUE-axios與fetch結構類似
const item = {
Key: "AAAAAA",
Value: "36d04a9d74392c727b1a9bf97a7bcbac"
};
//get訪問
axios.get(`${uri}/Page/${self.PageIndex}`)//請求地址
.then(response => (self.sites = response.data))//結果處理//返回結果全部早response.data中
.catch(error => console.error('Unable to get items.', error));//錯誤處理
//post訪問
axios({
method: 'post',//接口訪問方式GET\POST
url: `${uri}/insert`,//接口訪問地址
data: item//接口需要的參數
})
.then(response => (console.log(response.data)))
.catch(error => console.error('Unable to get items.', error));