Search code examples
c#asp.net-mvchttphandlerashxihttphandler

How can I call a method that's defined in an Http Handler file (.ashx) in my controller (ASP.NET MVC)?


I am completely new to .ashx and Http Handlers. But, what I want to do is call a method that's defined in my .ashx file from within my controller.

For example, I have my .ashx defined as follows:

public class proxy : IHttpHandler {

    public void ProcessRequest (HttpContext context) {

        HttpResponse response = context.Response;
...

Now, in my controller, I want to do something like:

[HttpPost]
public int PostPicture(HttpRequestMessage msg)
{
    proxy.ProcessRequest(...);
...

I know that you can call the ashx by navigating to the URL (http://server/proxy.ashx?ProcessRequest), but I don't think this is what I need. I want to call the ashx method from inside my controller. Forgive me if this is not a recommended approach- as I said, I'm new to ashx and not sure of the appropriate way to implement them.

  1. Is the above even recommended, and if so how can I accomplish this?
  2. If the above isn't recommended, what's an alternate way I can accomplish this?

Solution

  • You should extract the logic from your proxy class in another helper class. That extracted method should not have a direct reference to HttpContext but just the required data, for example, byte[] imageData. Call this method from both places in your code (assuming you need to keep the handler for compatibility).