此系列使用Asp.net構建前后端分離的博客網站,
創建一個asp.net專案


我們這里使用的是空模板,把Https配置去掉(安全先不配置)
構建webapi介面有很多方法,在這里我們選擇最簡單的2種方式進行搭建,
1.WebForm
創建一個webForm

打開表單的服務器邏輯代碼檔案
添加如下方法
【注意:其方法必須添加WebMethod特性,并設定為靜態的】
[WebMethod] public static string SayHello() { return "Hello,Asp.Net"; }
匯入JQuery,之后將使用ajax請求后端服務器
在這里我使用nuget安裝


撰寫前端頁面通過ajax請求
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8" /> 5 <title>首頁</title> 6 </head> 7 <body> 8 <button id="click">點我</button> 9 </body> 10 </html> 11 12 <script src="Scripts/jquery-3.4.1.min.js"></script> 13 <script type="text/javascript"> 14 15 //入口 16 $(document).ready(function () { 17 18 //系結事件 19 $('#click').click(function () { 20 //ajax 21 $.ajax({ 22 url: "Home.aspx/SayHello", 23 type: "post", 24 contentType: 'application/json; charset=utf-8', 25 dataType: "json", 26 success: function (res) { 27 28 alert(res.d); 29 }, 30 error: function () { 31 alert('請求失敗'); 32 } 33 }); 34 }); 35 }); 36 </script>
在瀏覽器中我們看到,已經取得了后端的資料

2.使用一般處理程式
創建一個一般處理程式

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/4461.html
標籤:ASP.NET
下一篇:使用ASP.NET Core 3.x 構建 RESTful API - 3.3 狀態碼、錯誤/故障、ProblemDetails
