Asp.net learning record (a) using asp.net build webAPI Interface

This series uses the front and rear end Asp.net build separate blog site.

Create a asp.net project

We use here is an empty template, remove the Https configuration (not the first security configuration)

There are many ways to build webapi interfaces, here we choose the simplest way to build two kinds.

1.WebForm

Create a webForm

 

Open the form's code file server logic

Add the following method

[Note: The methods must add the WebMethod properties, and set static]

[WebMethod]
public static string SayHello()
{
    return "Hello,Asp.Net";
}

 Introducing JQuery, then the back-end server a request using ajax

Here I use nuget installation

 

 

 

 

 Write the front page by ajax request

 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.使用一般处理程序

创建一个一般处理程序

 

 

 

Guess you like

Origin www.cnblogs.com/Fasty/p/12016270.html