场景
ASP.NET中新建Web网站并部署到IIS上(详细图文教程):
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/107199747
在上面博客中已经将网站部署到了IIS上。
怎样对前端的请求进行响应普通文本和JSON数据以及怎样获取get和post请求参数。
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。
实现
一般处理程序ashx
如果在一个html页面向服务器端请求数据,可用ashx作为后台页面处理数据。ashx适合用作数据后台处理,相当于WebForm中的aspx.cs文件或aspx.vb文件。
首先在项目下新建Handler目录并在此目录下添加新建项-一般处理程序。这里叫Badao.ashx
新建成功后
这样能返回最简单的文本数据,修改其代码为
context.Response.ContentType = "text/plain";
context.Response.Write("公众号:霸道的程序猿");
然后运行项目,访问
http://localhost:3526/Handler/BaDao.ashx
怎样获取get请求的参数
string param = context.Request.QueryString["gongzhonghao"];
那么就可以通过以下方式传递参数
http://localhost:3526/Handler/BaDao.ashx?gongzhonghao = 霸道的程序猿
怎样返回Json数据
context.Response.ContentType = "application/json";
string result = "[{\"Result\":\""+msg+"\"}]";
context.Response.Write(result);
设置响应类型并构建JSON数据然后返回
怎样接受POST请求的数据
为了构建前端POST请求,在项目下新建Views目录,在目录下新建User.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My Test ashx</title>
<script type="text/javascript" src="../js/jquery-1.6.4.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btn_Test").click(function () {
debugger
$.ajax({
type: "post",
url: "../Handler/BaDao.ashx",
datatype: "text",
data: { "gongzhonghao": "霸道的程序猿" },
success: function (data) {
debugger
$("#label1").html(data[0].Result);
}
});
});
});
</script>
</head>
<body>
<button type="button" id="btn_Test">Test</button>
<label id="label1"></label>
</body>
</html>
在页面中引入了Jquery所以还需要添加并引入Jquery
然后修改后台ashx为
context.Response.ContentType = "application/json";
//获取post请求数据
string param = context.Request.Form["gongzhonghao"];
string msg = "公众号:霸道的程序猿";
msg = param;
//构建json数据
string result = "[{\"Result\":\""+msg+"\"}]";
context.Response.Write(result);
然后运行项目,点击按钮
示例代码下载
https://download.csdn.net/download/BADAO_LIUMANG_QIZHI/12589864