Asp.net 学习记录(一)使用asp.net 构建webAPI接口

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

创建一个一般处理程序

 

 

 

posted @ 2019-12-10 14:05  Fasty  阅读(940)  评论(0编辑  收藏  举报