asp.net 通过IHttpModule开发接口

实现IHttpModule接口,处理AcquireRequestState事件

1、创建asp.net空项目,添加asp.net module,命名为MyModule1.cs

2、添加Context_AcquireRequestState方法

using Newtonsoft.Json;
using System;
using System.Web;

namespace WebApplication1
{
    public class MyModule1 : IHttpModule
    {
        /// <summary>
        /// You will need to configure this module 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 IHttpModule Members

        public void Dispose()
        {
            //clean-up code here.
        }

        public void Init(HttpApplication context)
        {
            // Below is an example of how you can handle LogRequest event and provide 
            // custom logging implementation for it
            context.LogRequest += new EventHandler(OnLogRequest);
            context.AcquireRequestState += Context_AcquireRequestState;
        }

        private void Context_AcquireRequestState(object sender, EventArgs e)
        {
            var context = sender as HttpApplication;
            var info = new
            {
                name = "xiaowang",
                age = 21,
                sex = "男"
            };
            var path = context.Request.Path;
            if ("/queryInfo3".Equals(path))
            {
                // 防止调用两次
                context.CompleteRequest();
                context.Response.ContentType = "application/json";
                context.Response.Write(JsonConvert.SerializeObject(info));
                context.Response.Flush();
            }
        }

        #endregion

        public void OnLogRequest(Object source, EventArgs e)
        {
            //custom logging logic can go here
        }
    }
}

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

<?xml version="1.0"?>
<configuration>
  <system.webServer>
    <modules>
      <add type="WebApplication1.MyModule1" name="/queryInfo3"/>
    </modules>
  </system.webServer>
</configuration>
  1. 访问接口:

  2. http://localhost:64683/queryInfo3

  3. 返回数据:

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

     

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值