0

can anyone tell me how to create Custom Hander (.ashx) file. Requirement: When a request come to my application for a .pdf, I want to invoke that .ashx handler. The .ashx handler will have logic to show the file or not.

My incoming path would be "http://www.domainname.com/Content/PDF/ABC.pdf". This URL should be handled by a "http://www.domainname.com/Handler.ashx" file.

I would like to know how to create, map, and register the handler in my application

Thanks in advance.

shakti
  • 191
  • 1
  • 8
  • 21

1 Answers1

0

Why you need an HTTPHandler if you are working with ASP.NET MVC, Use an Action method to server your file content. You can do most of the things you do with an HttpHandler in an Action method. You can do the routing of the action as you wish like http://domainname.com/content/abc can return the abc.pdf file

You should not directly let the browser to access the resource (PDF). Instead you give access via an action method. Read the file Id /name in the action method from the request and read the file and output it. Assuming that you have an action method like below in your ResourceController

public ActionResult GetFile(string id)
{
   string fullFilePath=somefullpathvariable+"//"+id+".pdf";
   return File(fullFilePath, "application/pdf", Server.UrlEncode(id+".pdf"));
}

Now users can access this like

http://www.yourdomain.com/Resource/awesomemvc

Now this can return a file called awesomemvc.pdf from a location which is stored in your server and your someFullPathVariable holds the path to that location

Shyju
  • 214,206
  • 104
  • 411
  • 497
  • i initially opted for mvc routing solution only. But!!, my url "http://www.domainname.com/Content/PDF/ABC.pdf" directly gets executed and doesnt go through route defined. routes.RouteExistingFiles = true; routes.MapRoute("PDFRoute", "Content/PDF/{id}", new { controller = "User", action = "GetPdf", id = UrlParameter.Optional}); – shakti May 23 '12 at 12:06
  • @shakti: It will go thru if you are exposing it via an action method. See my updated answer. – Shyju May 23 '12 at 12:17
  • Please understand my requirement: In Google Search my application url shows up. I want that url to be accessible only to logged in customers. The url is http://www.domainname.com/Content/PDF/ABC.pdf (with .pdf, extension) Now i want to route that to my controller and action. For that i have coded. routes.RouteExistingFiles = true; routes.MapRoute("PDF","Content/PDF/{id}",new { controller = "User", action = "GetPdf" }); Then too the pdf file directly gets opened up without going though my defined route. The same code i have added in my sample project and it works over there.(strange!!!) – shakti May 23 '12 at 13:38