HttpHandler 101 FAIL

2019-02-11 00:13发布

问题:

When I add an HTTP handler:

<add verb="*" path="*test.aspx" type="Handler"/>

With the class:

using System;
using System.Web;

public class Handler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        context.Response.Write("Hello World");
    }

    public bool IsReusable
    {
        get { return false; }
    }

}

My ASP.NET application dies with the error "Could not load type 'Handler'." when I try to access http://localhost:port/mysite/this-is-a-test.aspx.

I thought maybe it was a namespace issue, so I tried what follows, but got the same "Could not load type 'Test.Handler'." error.

<add verb="*" path="*test.aspx" type="Test.Handler, Test"/>

With the class:

using System;
using System.Web;

namespace Test
{

    public class Handler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Write("Hello World");
        }

        public bool IsReusable
        {
            get { return false; }
        }

    }

}

I knew I was getting rusty with ASP.NET, but I'm without a clue on this one.

回答1:

I guess you are using a web site project in contrast of web application project. In this case you need to put the code behind file of your handler (Handler.cs) in the special App_Code folder. The markup file (Handler.ashx) may be at the root of your site:

<%@ WebHandler Language="C#" Class="Handler" CodeBehind="Handler.cs" %>

Then you can directly declare your handler in web.config:

<add verb="*" path="*test.aspx" type="Handler"/>


回答2:

When the Handler is a class in my App_Code directory the following works for me:

    <add verb="*" path="*test.aspx" type="Test.Handler,__Code"/>

(I've only added handlers for whole prefixes like "*.test").



回答3:

By default asp.net Pagerhandlerfactory object will handle all the .aspx resource request.