开发者

Do I use a web service or a HttpHandler to serve images?

very simple question for you.. To serve Images is better a web serv开发者_开发知识库ice or a HttpHandler in asp.net c# ?

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

thanks


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.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜