博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
IHttpHandler处理请求api
阅读量:4566 次
发布时间:2019-06-08

本文共 1565 字,大约阅读时间需要 5 分钟。

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

研究后,可用此法实现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处理请求.

转载于:https://www.cnblogs.com/mirrortom/p/9232887.html

你可能感兴趣的文章
hash冲突的解决方法
查看>>
Asp.Net webconfig中使用configSections的用法
查看>>
mysql 二进制日志
查看>>
阻止putty变成inactive
查看>>
TP框架代码学习 学习记录 3.2.3
查看>>
doc文档生成带目录的pdf文件方法
查看>>
js数组,在遍历中删除元素(用 for (var i in arr)是无效的 )
查看>>
通过前端上传图片等文件的方法
查看>>
在 OC 中调用 Swift 代码
查看>>
Android仿腾讯应用宝 应用市场,下载界面, 有了进展button
查看>>
安卓|五大逆向软件下载
查看>>
5 OK6410裸机调试(不用Jlink)
查看>>
“模板”学习笔记(5)-----编译器在处理函数模板的时候都干了啥
查看>>
教你用shell写CGI程序
查看>>
窗口 对话框 Pop Dialog 示例
查看>>
ubuntu(centos) server安装vmware tools
查看>>
数据结构之最大不重复串
查看>>
为什么要配置sdk-tools/platform-toools?
查看>>
自己动手开发更好用的markdown编辑器-07(扩展语法)
查看>>
maven dependency:tree中反斜杠的含义
查看>>