创建接口的方式有很多,像是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);
}