asp.net 通过IHttpHandler开发接口

     实现IHttpHandler接口,在web.config中配置处理器

  1. 创建asp.net web application(.net framework)空项目
  2. 添加空项 asp.net Handler,命名为queryInfo.cs
  3. 实现ProcessRequest方法 
using System;
using System.Web;
using Newtonsoft.Json;

namespace WebApplication1
{
    public class queryInfo : IHttpHandler
    {
        /// <summary>
        /// You will need to configure this handler in the Web.config file of your 
        /// web and register it with IIS before being able to use it. For more information
        /// see the following link: https://go.microsoft.com/?linkid=8101007
        /// </summary>
        #region IHttpHandler Members

        public bool IsReusable
        {
            // Return false in case your Managed Handler cannot be reused for another request.
            // Usually this would be false in case you have some state information preserved per request.
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            //write your handler implementation here.
            var info = new
            {
                name = "xiaowang",
                age = 21,
                sex = "男"
            };
            context.Response.ContentType = "application/json";
            context.Response.Write(JsonConvert.SerializeObject(info));
            context.Response.Flush();
        }

        #endregion
    }
}

     4、在web.config中增加如下节点

  1. <?xml version="1.0"?>
    <configuration>
      <system.webServer>
        <handlers>
            <add name="queryInfo" path="/queryInfo" verb="GET" type="WebApplication1.queryInfo,WebApplication1"/>
        </handlers>
      </system.webServer>
    </configuration>

     

  2. 访问接口:

  3. http://localhost:64683/queryInfo

  4. 返回数据:

  5. {"name":"xiaowang","age":21,"sex":"男"}

     

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值