asp.net 通过IHttpHandler开发接口

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

  1. 创建asp.net web application(.net framework)空项目
  2. 添加空项 asp.net Handler,命名为queryInfo.csasp.net 通过IHttpHandler开发接口_第1张图片
  3. 实现ProcessRequest方法 
using System;
using System.Web;
using Newtonsoft.Json;

namespace WebApplication1
{
    public class queryInfo : IHttpHandler
    {
        /// 
        /// 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
        /// 
        #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. 
    
      
        
            
        
      
    

     

  2. 访问接口:

  3. http://localhost:64683/queryInfo

  4. 返回数据:

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

     

你可能感兴趣的:(asp.net,C#)