实现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>
-
访问接口:
-
返回数据:
-
{"name":"xiaowang","age":21,"sex":"男"}
博客介绍了在ASP.NET中实现IHttpModule接口处理AcquireRequestState事件的方法。先创建空项目并添加名为MyModule1.cs的ASP.NET模块,添加Context_AcquireRequestState方法,在web.config中增加节点,还给出了访问接口及返回数据相关信息。
187

被折叠的 条评论
为什么被折叠?



