[ASP.Net ]利用ashx搭建简易接口

转载:https://blog.csdn.net/ZYD45/article/details/79939475

创建接口的方式有很多,像是Web api,nodejs等等

今天,主要介绍,利用ashx的方式,来搭建一个简易的api


  1. 首先,利用VS编辑器,创建一个空的web应用程序

  2. 生成的项目文件

  3. 为此程序,添加一个新项,选择“一般处理程序”,可以看到文件后缀为.ashx

    若是生成后,重命名,不仅只改文件的名字,还要查看标记,更改标记里的信息

  4. 然后我们选择“启动”

    在生成的localhost网站的url里,增添“/ashx文件名.ashx",就可以看到如下信息

  5. 要是想返回json文件,修改下 context.Response.ContentType

    然后,返回的信息要组装成json字符串,

    当然.Net也提供了一些转json的方法,可以自行百度下

  6. context.Response.ContentType = "application/json";
  7. 这时候,再去访问,就可以在浏览器的Network中,看到返回的是json对象

  8. 要是想解析get方法方法传过来的参数
  9. string method = context.Request.QueryString["method"];//context.Request.QueryString["Get参数名"]
     

    这时候 method得到的就是“Login”这个值,

  10. 要是解析POST方法访问的参数,用context.Request.Form["POST参数名"]

    For Example

    前端用,ajax访问


  11. $.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就用


  12. string userID=context.Request.Form["userID"];//Admin

    string password=context.Request.Form["password";];//123


 

  1. 处理跨域访问

          只需处理下请求头部即可

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

posted on 2019-10-31 10:38  秋天  阅读(6861)  评论(1编辑  收藏  举报

导航