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

What are the benefits of using an ashx, or handler? Also, do I need them if I use MVC (and why not)?
Does the framework matter (2.0+)?
Why would I want to use a handler? I was recently recommended to use one for retrieving an image but I don't know why.
Thank you for your time.
Edit - is a handler faster?

Just a few examples:
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>
Returning REST-based XML or JSON data to AJAX code on the client.
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.

Related

Can Webapi be used in an application which is not excessed by any external application?

I'd read it somewhere that whenever one needs to do data intensive work then Webapi could be used. Ex: autocomplete textbox where we get data from using ajax on key press.
Now someone told me that Webapi shouldn't be used within applications which are not externally accessed. Rather action should be used to the same work as it is capable of returning the data back in a similar fashion to webapi.
I'd like to know your suggestions over it.
Depends on how you look at it. If all you need is ajax-ification of your controller actions, then you really don't need Web-API. Your actions can return a JsonResult and it is very easy to consume that from your client side through an AJAX call.
Web-API makes it easy for you to expose you actions to external clients. It supports HTTP protocol and Json and XML payloads automatically, out of the box, without you writing the code for it. Now, there is nothing preventing you from consuming the same Web-API actions from your own internal clients in an AJAX manner.
So the answer to your question depends on your design. If you don't have external clients, then there is no string need for you to have Web-API. Your standard controller actions can do the job.

How to render Web Api to a view?

I wrote some code in webapi ValueConroller. When I try to execute it I'm getting JSON data which is by default saving to text file (IE 8.0), XML output when tried with Mozilla Firefox .
I am not sure how to display my List<country> which will be having list of countries and i am writing this method in value controller like
public IEnumarable<countrylist> getcounrty()
{
obj.method1().tolist(); // method1 will return list<country> where country is a class in my BLL
}
I want the method output to be bonded with Dropdownlist . Becoz there is no VIEW is webapi I am confused how to do it
Any ideas are appreciated.
EDIT : konckout.js is a alternative ? my colleagues ad-viced me so any best alternative mates
Web API and MVC have different purposes.
The purpose of ASP.NET Web API is to build HTTP-based web services (also sometimes called REST services). Out of the box, it only supports
JSON
XML
although you can implement other formatters yourself, if you need to exchange data in another format. In theory, you could write a custom formatter to produce HTML, but there's no reason to do that.
If you need to produce HTML, then use ASP.NET MVC.

MVC4 Razor View Batch Methods

I have a HTML helper which shows translated resources depending on some business logic. Now this helper uses a webservice to load the translated resources.
The problem is that it takes very long if we have to make a webservice call for each single translated resource. Of course we cache the result but the initial call still takes very long.
What would be great would be if we could kind of batch process the translated resources. Like we collect all the resources that are to be rendered and then after we know which resources have to be translated only make one webservice call which translates all the resources for us and renders it to the correct places in the view.
Is there some mechanism in Razor templates for this?

What is an efficient way to create/manage RESTful API with grails?

I've built my first grails application. My URL mappings are what the default application provides:
static mappings = {
"/$controller/$action?/$id?"{
constraints {
// apply constraints here
}
}
"/"(view:"/index")
"500"(view:'/error')
}
Senario
I have a controller called ColorController with actions save and list. It simply does something like this:
def save () {
def colorInstance = new Color(params)
colorInstance.save(flush: true)
}
def list () {
[colorList: Color.list, colorTotal: Color.count()]
}
I would like to build a simple API for these actions.
The save action should accept parameters as JSON and provide a successful message if the records save.
The list action should provide the list as JSON
Questions
Should I make a separate URL mapping for api? (e.g. http://<domain>/<app>/rest/controller/action)
Should I be making a separate controller for my API's
I am using spring security plugin for authentication. But at some point I might want to authenticate the restful api as well. What are some solutions for that?
If I use the same controller, how can I modify these simple actions to do what I need.
Before even looking below for my opinion/answers I would suggest to visit this SO Question for the basic understanding of RESTful WS in Grails.
Opinions:
"The save action should accept parameters as JSON and provide a successful message if the records save" - Save is mapped to POST RESTful. Instead of binding a JSON body to params it is bound to the request. In order to access the JSON object you just need to use request.JSON in the action method.
request.JSON instanceof JSONObject
"The list action should provide the list as JSON" - list() action is mapped to a GET Request and you can render the map as JSON in the list() as below
//Controller list()
import grails.converter.JSON
def list () {
[colorList: Color.list, colorTotal: Color.count()] as JSON
}
Answers to Questions:-
Should I make a separate URL mapping for api?
Abiding by the basics of REST, the client should only access the resource (Color in this case) and should not bother about the underlying controller or action. The server side logic should be abstracted from the client. URL Mapping is what the client would use to as form of request. I would have something like this in my url mapping for Color Resource.
/color/$id?(resource: "color")
or
/color/$id?(controller: 'color'){
action = [GET: "list", POST: "save"]
}
Should I be making a separate controller for my API's? - Depends on the way the App is designed. You also can have the above controller as the API. For example, currently I am working on a grails app which used AngularJS in the front End which connects to the Grails APP RESTFully. In order to achieve I had a RestClientController which works as an API to Angular. The rationale behind having a REST api in the same app is that in future we can expose the underlying service to external clients other than the Angular client present in the app itself.
I am using spring security plugin for authentication. But at some point I might want to authenticate the restful api as well. What are some solutions for that? - You can use Spring Security here as well. In my case I am using the plugin and I secure the controller by using the plugin's annotated component #Secured. I have custom OAuth enabled as well for authorization which interacts to the company wide LDAP and AD Groups.
If I use the same controller, how can I modify these simple actions to do what I need. - I think you would have got the answer to this question by now (after going through the SO question I mentioned above). Here is my opinion, controller actions can route to appropriate service classes which does the business implementations based on the request parameters.
For example,
//Action
def show(){
if(params.id){
colorService.getColor()
} else {
colorService.searchColor()
}
}
In the above example, the url mapping would be /color/123 or /color. In the former case, it will get the color and in the later it will search the colors

Is it recommended to return json data from a web api method in ASP.NET MVC 4?

Is it recommended to return json data from a web api method ?
This I am using for jqgrid.
I am using WebApi for all other operations like Get, Update, Delete etc...
Thanks
WebApi supports Content Negotation. This means that it will give you what you ask for. WebApi will inspect the header of your request and will then return the data in the correct format.
In case of an AJAX application using jqGrid, you will probably ask for JSON. That's the easiest format to use in JavaScript.
If someone else would call your WebApi method and ask for Xml, your method would return Xml to the caller.