Do I use a web service or a HttpHandler to serve i

2019-04-02 13:26发布

问题:

very simple question for you.. To serve Images is better a web service or a HttpHandler in asp.net c# ?

what is the difference ? Why I should prefer one instead another ?

thanks

回答1:

I would go with an HttpHandler. Its more efficient because it doesn't go through the normal page request pipeline, and is the earliest point where you have access to request. Phil Haack has a great boilerplate template.



回答2:

I would suggest a HttpHandler because it can transfert binary data efficiently. Web service would

  • force you to load the entire file in memory before sending it
  • base64encode your file (=> +30% size)

This is the c# code for the handler :

public class ImageHandler : IHttpHandler
{
    public bool IsReusable
    {
        get { return true; }
    }

    //your handler will need somehing like http://xxxxx/Image.ashx?file=toto.png
    //(humm I suggest you to put adamantite++ validations here :p)
    public void ProcessRequest(HttpContext context)
    {
        string fileName = context.Request.QueryString["file"];
        context.Response.WriteFile(fileName);
    }
}

And this is the configuration you need to add :

<configuration>
...
  <system.webServer>
    <handlers>
    <add name="MyImages" verb="*" path="Image.ashx" type="MyApp.ImageHandler, MyApp/>

I hope this help you.



回答3:

Of course IHttpHandler is the way to go. Becuase..

  1. HttpHandler requests are less bandwidth costly because the request-response are not decorated with XML like web-services.

  2. Webservices are used in entirely different context like exposing end-points for SOA applications. So webservices are really not prime candidate for your objective.



回答4:

You could use either, from what you've supplied I would use a handler as it's better suited in my opinion for this type of request.

Web Services are more about surfacing a series of operations for consumption by a third party, you've chosen to expose content in a particular way (maybe to satisfy some kind of authorisation behaviour), in these cases you're added additional logic to how a request is dealt with i.e. you're handling the request in a custom manner therefore I'd go with a handler.