Can ASP.NET Routing be used to create “clean” URLs for .ashx (IHttpHander) handlers?

前端 未结 5 1885
温柔的废话
温柔的废话 2020-11-30 03:19

I have some REST services using plain old IHttpHandlers. I\'d like to generate cleaner URLs, so that I don\'t have the .ashx in the path. Is there a way to us

5条回答
  •  被撕碎了的回忆
    2020-11-30 04:01

    I actually like Joel's solution better, as it doesn't require you to know the type of handler while you're trying to setup your routes. I'd upvote it, but alas, I haven't the reputation required.

    I actually found a solution which I feel is better than both mentioned. The original source code I derived my example from can be found linked here http://weblogs.asp.net/leftslipper/archive/2009/10/07/introducing-smartyroute-a-smarty-ier-way-to-do-routing-in-asp-net-applications.aspx.

    This is less code, type agnostic, and fast.

    public class HttpHandlerRoute : IRouteHandler {
    
      private String _VirtualPath = null;
    
      public HttpHandlerRoute(String virtualPath) {
        _VirtualPath = virtualPath;
      }
    
      public IHttpHandler GetHttpHandler(RequestContext requestContext) {
        IHttpHandler httpHandler = (IHttpHandler)BuildManager.CreateInstanceFromVirtualPath(_VirtualPath, typeof(IHttpHandler));
        return httpHandler;
      }
    }
    

    And a rough example of use

    String handlerPath = "~/UploadHandler.ashx";
    RouteTable.Routes.Add(new Route("files/upload", new HttpHandlerRoute(handlerPath)));
    

提交回复
热议问题