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

StackOverflow https://stackoverflow.com/questions/16546629

문제

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?
도움이 되었습니까?

해결책

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).

다른 팁

Here are two ways to call pass current httpcontext which in Controller to .ashx :

  1. HttpContext context = HttpContext.ApplicationInstance.Context;

  2. HttpContext context = (HttpContext)HttpContext.GetService(typeof(HttpContext));

Then you could call it :

[HttpPost]
public int PostPicture(HttpRequestMessage msg)
{
    HttpContext context = HttpContext.ApplicationInstance.Context;
    proxy.ProcessRequest(context);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top