以下是使用VB.NET实现的方案,分别针对传统ASP.NET(System.Web)和ASP.NET Core 两种环境,实现无需手动配置handlers
,仅将 DLL 放入bin
目录即可处理 HTTP 请求的功能。
一、传统ASP.NET(System.Web)方案:自动注册 HTTP 模块
通过PreApplicationStartMethod
特性实现模块自动注册,放入bin
目录后即可生效。
VB.NET自动注册HTTP模块处理请求
Imports System.Web' 程序集级特性:指定应用启动时自动执行的初始化方法
<Assembly: PreApplicationStartMethod(GetType(UploadToolInitializer), "Initialize")> Namespace XiaoYaoWebCore' 自定义HTTP模块,处理请求逻辑Public Class UploadToolModuleImplements IHttpModulePublic Sub Init(context As HttpApplication) Implements IHttpModule.Init' 注册请求开始事件AddHandler context.BeginRequest, AddressOf OnBeginRequestEnd SubPrivate Sub OnBeginRequest(sender As Object, e As EventArgs)Dim app As HttpApplication = DirectCast(sender, HttpApplication)Dim request As HttpRequest = app.Context.RequestDim response As HttpResponse = app.Context.Response' 只处理特定路径的请求If request.Path.StartsWith("/UploadTool", StringComparison.OrdinalIgnoreCase) Then' 这里是你的业务处理逻辑response.ContentType = "text/plain"response.Write("VB.NET自动加载模块处理成功:" & DateTime.Now.ToString())response.End() ' 终止后续处理End IfEnd SubPublic Sub Dispose() Implements IHttpModule.Dispose' 清理资源(如果需要)End SubEnd Class' 初始化器:负责自动注册模块Public NotInheritable Class UploadToolInitializerPrivate Sub New()End Sub' 应用启动时自动调用此方法Public Shared Sub Initialize()' 向ASP.NET管道注册模块HttpApplication.RegisterModule(GetType(UploadToolModule))End SubEnd Class
End Namespace
二、ASP.NET Core 方案:自动扫描并注册中间件
主项目提前配置扫描逻辑,DLL 中的中间件会被自动发现并注册。
1. DLL 中的中间件实现(VB.NET)
VB.NET ASP.NET Core中间件
Imports Microsoft.AspNetCore.Http
Imports System.Threading.TasksNamespace XiaoYaoWebCorePublic Class UploadToolMiddlewarePrivate ReadOnly _next As RequestDelegate' 构造函数,接收下一个中间件Public Sub New(next As RequestDelegate)_next = nextEnd Sub' 处理请求的核心方法Public Async Function InvokeAsync(context As HttpContext) As Task' 匹配特定路径If context.Request.Path.StartsWithSegments("/UploadTool") Thencontext.Response.ContentType = "text/plain"Await context.Response.WriteAsync("VB.NET Core中间件自动处理成功:" & DateTime.Now.ToString())Return ' 处理完成,不再调用下一个中间件End If' 不匹配则传递给下一个中间件Await _next(context)End FunctionEnd Class
End Namespace
2. 主项目扫描逻辑(Program.vb)主项目扫描并注册中间件
Imports Microsoft.AspNetCore.Builder
Imports Microsoft.AspNetCore.Hosting
Imports System.Reflection
Imports System.IOModule ProgramSub Main(args As String())Dim builder = WebApplication.CreateBuilder(args)Dim app = builder.Build()' 扫描bin目录中的所有DLL,自动注册中间件ScanAndRegisterMiddleware(app)app.Run()End Sub' 扫描bin目录并注册符合约定的中间件Private Sub ScanAndRegisterMiddleware(app As WebApplication)Dim binPath = Path.Combine(app.Environment.ContentRootPath, "bin")If Not Directory.Exists(binPath) Then ReturnFor Each dllFile In Directory.GetFiles(binPath, "*.dll", SearchOption.AllDirectories)Try' 加载DLLDim assembly = Assembly.LoadFrom(dllFile)' 查找符合约定的中间件(类名以Middleware结尾,有正确的构造函数和InvokeAsync方法)For Each type In assembly.GetTypes()If type.Name.EndsWith("Middleware") AndAlso type.GetConstructor({GetType(RequestDelegate)}) IsNot Nothing AndAlsotype.GetMethod("InvokeAsync") IsNot Nothing Then' 注册中间件app.Use(Function(context, next)' 反射创建中间件实例并调用Dim middleware = Activator.CreateInstance(type, next)Return CType(type.GetMethod("InvokeAsync").Invoke(middleware, {context}), Task)End Function)End IfNextCatch ex As Exception' 忽略加载失败的DLL(如系统组件)Console.WriteLine($"加载DLL失败:{dllFile},错误:{ex.Message}")End TryNextEnd Sub
End Module
实现说明
传统ASP.NET方案工作原理:
- 通过
PreApplicationStartMethod
特性,ASP.NET在应用启动时会自动执行UploadToolInitializer.Initialize
方法 - 该方法通过
HttpApplication.RegisterModule
向管道注册自定义模块 - 模块在
BeginRequest
事件中拦截特定路径请求并处理 - 只需将编译后的 DLL 放入项目
bin
目录,无需修改web.config
的handlers
或modules
ASP.NET Core 方案工作原理:
- 主项目在启动时扫描
bin
目录中的所有 DLL - 自动发现符合约定(类名以
Middleware
结尾)的中间件类 - 通过反射机制将中间件注册到请求处理管道
- 中间件会拦截匹配
/UploadTool
路径的请求并处理
使用方法
- 将上述代码编译为 DLL(如
XiaoYaoWebCore.dll
) - 直接放入对应ASP.NET或ASP.NET Core 项目的
bin
目录 - 启动 IIS Express,访问
http://localhost:端口/UploadTool
即可看到处理结果
这种方式实现了 “仅放 DLL 到 bin 目录即可处理请求” 的需求,无需手动配置handlers
。