在 ASP .NET 中,可以通过实现 IHttpHandler 或者 IHttpModule 接口来自定义接口的请求路径。
方法1:
实现 IHttpHandler 接口 推荐
public class MyHandler : IHttpHandler
{
public bool IsReusable => true;
public void ProcessRequest(HttpContext context)
{
// context.Request.Body 获取body 参数
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World!");
}
}
在 web.config 中配置自定义路径:
<configuration>
<system.webServer>
<handlers>
<add name="MyHandler" path="myhandler/*" verb="*" type="MyHandler"/>
</handlers>
</system.webServer>
</configuration>
这样,当请求路径为 /myhandler/开头的接口时,就会调用 MyHandler 类的 ProcessRequest 方法。
方法2:
实现 IHttpModule 接口
public class MyModule : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.BeginRequest += Context_BeginRequest;
}
private void Context_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
HttpContext context = app.Context;
// 路径服务转发,可结合自定义 注解 切面 做分发逻辑
if (context.Request.Path.EndsWith("/mycustompath"))
{
// context.Request.Body 获取body 参数
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World!");
app.CompleteRequest();
}
}
}
在 web.config 中配置自定义路径:
<configuration>
<system.webServer>
<modules>
<add name="MyModule" type="MyModule"/>
</modules>
</system.webServer>
</configuration>
这样,当请求路径为 /mycustompath 时,就会调用 MyModule 类的 Context_BeginRequest 方法。
分类:
.net
« 上一篇: Java5的 线程并发库
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?