轉載:https://blog.csdn.net/ZYD45/article/details/79939475
創建接口的方式有很多,像是Web api,nodejs等等
今天,主要介紹,利用ashx的方式,來搭建一個簡易的api
-
首先,利用VS編輯器,創建一個空的web應用程序
-
生成的項目文件
-
-
為此程序,添加一個新項,選擇“一般處理程序”,可以看到文件后綴為.ashx
若是生成后,重命名,不僅只改文件的名字,還要查看標記,更改標記里的信息
-
然后我們選擇“啟動”
,
在生成的localhost網站的url里,增添“/ashx文件名.ashx",就可以看到如下信息
-
要是想返回json文件,修改下 context.Response.ContentType
然后,返回的信息要組裝成json字符串,
當然.Net也提供了一些轉json的方法,可以自行百度下
- context.Response.ContentType = "application/json";
-
這時候,再去訪問,就可以在瀏覽器的Network中,看到返回的是json對象
- 要是想解析get方法方法傳過來的參數
-
string method = context.Request.QueryString["method"];//context.Request.QueryString["Get參數名"]
這時候 method得到的就是“Login”這個值,
-
要是解析POST方法訪問的參數,用context.Request.Form["POST參數名"]
For Example
前端用,ajax訪問
-
$.ajax({
url:'localhost:4883/APITest.ashx?method=Login',
type:"POST",
dataType: "json",
data:{password:'123',userID:'Admin'},
success:function(data){
console.log(data);//返回的json數據
},
error:function(err){
console.log(err.responseText);//查看錯誤信息
})
ashx想要得到password 和userID就用 -
string userID=context.Request.Form["userID"];//Admin
string password=context.Request.Form["password";];//123
-
處理跨域訪問
只需處理下請求頭部即可
Web.Config添加(丟在configuration標簽內就行)
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="x-requested-with"/>
</customHeaders>
</httpProtocol>
</system.webServer>
請求方法里添加
public void ProcessRequest(HttpContext context)
{
context.Response.ClearHeaders();
context.Response.AppendHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
context.Response.AppendHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
context.Response.AppendHeader("X-Powered-By", "3.2.1");
context.Response.ContentType = "application/json";
string msg = string.Format(@"接口訪問成功");
string result = "[{\"Result\":\"" + msg + "\"}]";
context.Response.Write(result);
}
————————————————
版權聲明:本文為CSDN博主「29號同學」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/ZYD45/article/details/79939475