HTTP管道扩展

在ClownFish框架中,允许采用经典的 HttpModule/HttpHandler 模型来实现HTTP管道的扩展。



开发HttpModule

示例代码如下:

public class QueryModule : NHttpModule
{
    public override void ResolveRequestCache(NHttpContext httpContext)
    {
        // 检查当前请求是否映射到一个已定义的“服务接口”
        ApiAction action = ActionResolver.GetAction(httpContext);
        if( action == null )
            return;


        QueryHandler handler = new QueryHandler(action);
        httpContext.PipelineContext.SetHttpHandler(handler);
    }        
}

小结:

  • 开发过程和经典的 ASP.NET HttpModule类似,
  • 注意这里是 NHttpModule 基类,
  • 然后是重写基类的虚方法(而不是订阅事件)
  • 由HttpModule负责HttpHandler的实例化
  • 调用httpContext.PipelineContext.SetHttpHandler(handler);来启用HttpHandler实例

开发HttpHandler

(部分)示例代码如下:

internal class QueryHandler : IAsyncNHttpHandler
{
    private NHttpContext _httpContext;
    private ApiAction _action;
    private IDictionary<string, object> _args;


    public QueryHandler(ApiAction action)
    {
        _action = action;
    }

    public async Task ProcessRequestAsync(NHttpContext httpContext)
    {
        _httpContext = httpContext;

        if( await ValidateRequest() == false )
            return;

        _args = GetArgs();

        switch( _action.SourceType ) {
            case 1:
                await new SqlQueryExecutor(_httpContext, _action, _args).ExecuteAsync();
                break;

            case 2:
                await new HttpExecutor(_httpContext, _action, _args).ExecuteAsync();
                break;

            default:
                throw new InvalidOperationException($"无效的 SourceType = {_action.SourceType} 取值。");
        }
    }
}

小结:

  • HttpHandler要实现IAsyncNHttpHandler接口
  • 然后实现 ProcessRequestAsync 方法




检查 HttpModule 是否已加载

可以访问 Venus 查看进程的 【查看系统信息】,如下下图:

xx

xx

这里显示了所有已加载的HttpModule