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

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

    处理跨域访问

          只需处理下请求头部即可

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);
}

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

29号同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值