How to access RouteData from within an ASHX?

My web site has a handler (FileDownload.ashx) that deals with all file download requests.

I've recently migrated my site to ASP.NET 4.0, and it now uses routing extensively. Everything works fine when dealing with page requests (aspx), but it's not working with my handler - I encounter the following error:

Type '.Handlers.FileDownload' does not inherit from 'System.Web.UI.Page'.

This makes sense, as routing is only implemented in the page.

What steps do I need to take to be able to use routing and my .ashx together? I want to be able to extract RouteData.Values from the route.

public class FileDownload : IHttpHandler
{
}

I needed to hand craft a handler in the end, but it was easy enough: http://haacked.com/archive/2009/11/04/routehandler-for-http-handlers.aspx

.Net 4.0 does not natively support route handling for IHttpHandlers.


Sounds like an IIS problem.

Does this work if you try and use the ASP.NET Development Server (Cassini) ?

If you're using IIS6 you'll need to use Wildcard Application Mappings - see here.

You'll also still need to create your routes as per any ASPX page, like this:

public static void RegisterRoutes(RouteCollection routes)
{
    string[] allowedMethods = { "GET", "POST" };
    HttpMethodConstraint methodConstraints = new HttpMethodConstraint(allowedMethods);

    Route fileDownloadRoute = new Route("{foo}/{bar}", new FileDownload());
    fileDownloadRoute.Constraints = new RouteValueDictionary { { "httpMethod", methodConstraints } };

    routes.Add(fileDownloadRoute);
}

Have you done that? If so, i'd say your problem is definetely with IIS.

See here for a good article on ASP.NET 4 Routing for both IIS6 and IIS7.

Good luck!

链接地址: http://www.djcxy.com/p/46620.html

上一篇: Ninject与ASP.Net webforms和MVC

下一篇: 如何从ASHX内部访问RouteData?