What are the benefits of an ASHX handler file in asp.net?

≡放荡痞女 提交于 2019-11-29 01:30:56

Just a few examples:

  1. Dynamic image generation: You can write handlers that return data driven images by creating an ASHX handler that returns image data and then using that URL in your tags. e.g. <img alt="user's custom icon" src="Icon.ashx?username=bob"></img>

  2. Returning REST-based XML or JSON data to AJAX code on the client.

  3. Custom HTML: Return totally custom HTML for a page when the ASP.NET Web Forms or MVC framework is too restrictive

I believe this has been available since 1.0

The purpose of handlers in non-MVC projects is to provide some type of encoded response, outside of HTML. Typically, a handler would return XML (rss, RESTful, etc), JSON for jQuery or other Javascript, or sometimes just pure data such as file binary downloads. I've used handlers to even return special javascript to be excuted on the client, as a way of lazy-loading large binary or requirements on a "demand-only" approach. More or less, a handler would be used to return "anything but HTML".

In MVC, you would move away from handlers and utilize the Controller to return whatever data you like. So, in the method like:

mywebsite.com/restapi/content/56223

You RestfulContentController would have a method for Index(), that would NOT return a View(), but instead pure XML or JSON.

public class JSONContentController : Controller
{
  public JsonResult Index(int ContentID)
  {
    // get Content() by ContentID
    //

    // return a JSON version
    return Content().SerializeToJSON();
  }
}

They're very useful if your working in an environment where you do not have access to IIS but want to change things like far-future expiry response headers to optimize caching for files like css, images, JavaScript

For images you can do stuff like on the fly optimization so you can request images like image.jpg.ashx?w=180&quality=70 and then use the handler to deliver the image based on the settings passed in the querystring

aspx inherits page which implements IRequireSessionState. So if you call it via Ajax then asp.net needs to lock the session before further processing.

For ashx file it is stateless. Unless you inherit it from IRequireSessionState to manage state.

Use ashx for all Ajax calls and use aspx for purely asp.net page.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!