• ASP.NET自定义处理程序


    要创建自定义处理程序,可以创建一个实现IHttpHandler接口的类。

    该类有两个重要的参数:IsResuable属性和ProcessRequest方法。如果处理程序实例可以在不同的请求中重用,IsResuable就返回true。ProcessRequest方法接收带参数的HttpContext。HttpContext允许接收来自调用者的请求信息,并发回一个响应。

    下面的实例主要是客户端请求url:http://localhost:9287/CallCustomHandler 然后调用处理程序返回一个html。

    在VS中新建一个空网站:WebHandler,如图。

    新建一个类库SampleHandler添加类CustomHandler

    CustomHandler类的代码如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Web;
    
    namespace SampleHandler
    {
        public class CustomHandler:IHttpHandler
        {
            private string responseString = @"
                <DOCTYPE HTML>
                <html>
                <head>
                <meta charset=""UTF-8"">
                <title>Costom Handler</title>
                </head>
                <body>
                <h1>Hello from cumstom handler</h1>
                <h1>{0}</h1>
                <div>{1}</div>
                </body>
                </html>";
    
            public bool IsReusable
            {
                get
                {
                    return true;
                }
            }
    
            public void ProcessRequest(HttpContext context)
            {
                HttpRequest request = context.Request;
                HttpResponse response = context.Response;
                response.ContentType = "text/html";
                response.Write(string.Format(responseString, request.UserHostAddress, request.UserAgent));
            }
        }
    }

    在WebHandler跟目录下Web.config中配置

    <system.webServer>
        <handlers>
          <add name="CustomHandler" verb="*" path="CallCustomHandler" type="SampleHandler.CustomHandler,SampleHandler"/>
        </handlers>
      </system.webServer>
    

      运行效果图为

  • 相关阅读:
    【组合数学】 03
    【组合数学】 02
    【微积分】 10
    马未都说收藏:陶瓷篇(18、19)五彩瓷、斗彩
    马未都说收藏:陶瓷篇(1)历史朝代、陶器
    maven pom.xml常用标签 Exclusions plugins是什么意思
    Java日志记录工具SLF4J介绍
    Spring Context及ApplicationContext
    RabbitMQ中Queue详细介绍
    收藏专家马未都简介
  • 原文地址:https://www.cnblogs.com/simen-tan/p/5426149.html
Copyright © 2020-2023  润新知