在 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 2023-06-15 11:35  守望星空的那一边  阅读(45)  评论(0)    收藏  举报