随笔 - 4  文章 - 0 评论 - 1 阅读 - 6080
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

在 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 方法。

posted on   守望星空的那一边  阅读(35)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示