IHttpHandler处理请求api

使用IHttpHandler处理请求,实现webapi功能.

研究asp.net管道处理事件后,可用此法实现webapi功能.

 

测试环境 VS2017 WIN10 IIS10 集成模式

关键接口类两个 IHttpHandlerFactory 和 IHttpHandler 

 

处理过程

1.实现IHttpHandlerFactory,它的作用是指定由哪一个IHttpHandler来处理请求.在第7个事件时执行.

2.在第11个事件时,执行IHttpHandler.在这个处理类中,分析URL地址,使用反射找到对应的类和方法执行之.

具体做法

1.新建一个.net framework类库项目,添加两个类,分别实现IHttpHandlerFactory IHttpHandler  (注意添加System.Web程序集)

// 实现IHttpHandlerFactory

public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
{

  // 类的作用就是返回一个IHttpHandler

   return new ApiHandler();

}

// ApiHandler()类 实现IHttpHandler

public void ProcessRequest(HttpContext context)
{

  // 分解URL路径用于找类名和方法名
  string[] urlparts = context.Request.RawUrl.Split('/');

  string apiClassN = urlparts[1];
  string apiMethodN = urlparts[2];

  // 反射找到这个类,实现化之.并且传入context上下文对象

  Type webapiT = Assembly.GetExecutingAssembly().GetType(apiClassN, false, true);

  WebApiBase workapi = (WebApiBase)Activator.CreateInstance(webapiT, true);
  workapi.SetHttpContext(context);

  // 执行方法
  webapiMethod.Invoke(workapi, null);

  // 此至,完成请求

}

 

2.webconfig需要添加处理程序映射.注意path "*." ,它匹配 /user/info 这种不带扩展名的路径

<add name="FactoryHandler" path="*." verb="*" type="FactoryHandlerFactory" resourceType="Unspecified" preCondition="integratedMode" />

 

3.对于静态文件,不需要走处理管道,使用系统的静态文件处理模块.配置如下
<add name="StaticFile" path="*" verb="*" modules="StaticFileModule,DefaultDocumentModule,DirectoryListingModule" resourceType="Either" requireAccess="Read" />

 

4.可以建一个.net  framework类库项目,添加上述文件.挂到IIS下,使用集成模式.可以用于webapi处理请求.

 

5.示例代码

https://github.com/mirrortom/MyWebApi

posted @ 2018-06-27 11:01  mirrorspace  阅读(668)  评论(3编辑  收藏  举报