Rick Strahl's Weblog  

Wind, waves, code and everything in between...
.NET • C# • Markdown • WPF • All Things Web
Contact   •   Articles   •   Products   •   Support   •   Advertise
Sponsored by:
Markdown Monster - The Markdown Editor for Windows

Using the West Wind Web Toolkit to set up AJAX and REST Services


:P
On this page:

I frequently get questions about which option to use for creating AJAX and REST backends for ASP.NET applications. There are many solutions out there to do this actually, but when I have a choice - not surprisingly - I fall back to my own tools in the West Wind West Wind Web Toolkit. I've talked a bunch about the 'in-the-box' solutions in the past so for a change in this post I'll talk about the tools that I use in my own and customer applications to handle AJAX and REST based access to service resources using the West Wind West Wind Web Toolkit.

Let me preface this by saying that I like things to be easy. Yes flexible is very important as well but not at the expense of over-complexity. The goal I've had with my tools is make it drop dead easy, with good performance while providing the core features that I'm after, which are:

  • Easy AJAX/JSON Callbacks
  • Ability to return any kind of non JSON content (string, stream, byte[], images)
  • Ability to work with both XML and JSON interchangeably for input/output
  • Access endpoints via POST data, RPC JSON calls, GET QueryString values or Routing interface
  • Easy to use generic JavaScript client to make RPC calls (same syntax, just what you need)
  • Ability to create clean URLS with Routing
  • Ability to use standard ASP.NET HTTP Stack for HTTP semantics

It's all about options!

In this post I'll demonstrate most of these features (except XML) in a few simple and short samples which you can download. So let's take a look and see how you can build an AJAX callback solution with the West Wind Web Toolkit.

Installing the Toolkit Assemblies

The easiest and leanest way of using the Toolkit in your Web project is to grab it via NuGet:

West Wind Web and AJAX Utilities (Westwind.Web)

and drop it into the project by right clicking in your Project and choosing Manage NuGet Packages from anywhere in the Project.

InsertNuget

 

When done you end up with your project looking like this:

NewProjectAfterNuget

What just happened?

Nuget added two assemblies - Westwind.Web and Westwind.Utilities and the client ww.jquery.js library. It also added a couple of references into web.config: The default namespaces so they can be accessed in pages/views and a ScriptCompressionModule that the toolkit optionally uses to compress script resources served from within the assembly (namely ww.jquery.js and optionally jquery.js).

Creating a new Service

The West Wind Web Toolkit supports several ways of creating and accessing AJAX services, but for this post I'll stick to the lower level approach that works from any plain HTML page or of course MVC, WebForms, WebPages. There's also a WebForms specific control that makes this even easier but I'll leave that for another post.

So, to create a new standalone AJAX/REST service we can create a new HttpHandler in the new project either as a pure class based handler or as a generic .ASHX handler. Both work equally well, but generic handlers don't require any web.config configuration so I'll use that here.

In the root of the project add a Generic Handler. I'm going to call this one StockService.ashx. Once the handler has been created, edit the code and remove all of the handler body code. Then change the base class to CallbackHandler and add methods that have a [CallbackMethod] attribute.

Here's the modified base handler implementation now looks like with an added HelloWorld method:

using System;
using Westwind.Web;

namespace WestWindWebAjax
{
    /// <summary>
    /// Handler implements CallbackHandler to provide REST/AJAX services
    /// </summary>
    public class SampleService : CallbackHandler
    {

        [CallbackMethod]
        public string HelloWorld(string name)
        { 
            return "Hello " + name + ". Time is: " + DateTime.Now.ToString();
        }
    }
}


Notice that the class inherits from CallbackHandler and that the HelloWorld service method is marked up with [CallbackMethod]. We're done here. Services

Urlbased Syntax

Once you compile, the 'service' is live can respond to requests. All CallbackHandlers support input in GET and POST formats, and can return results as JSON or XML. To check our fancy HelloWorld method we can now access the service like this:

http://localhost/WestWindWebAjax/StockService.ashx?Method=HelloWorld&name=Rick

which produces a default JSON response - in this case a string (wrapped in quotes as it's JSON):

JSONOutput

(note by default JSON will be downloaded by most browsers not displayed - various options are available to view JSON right in the browser)

If I want to return the same data as XML I can tack on a &format=xml at the end of the querystring which produces:

<string>Hello Rick. Time is: 11/1/2011 12:11:13 PM</string>

Cleaner URLs with Routing Syntax

If you want cleaner URLs for each operation you can also configure custom routes on a per URL basis similar to the way that WCF REST does. To do this you need to add a new RouteHandler to your application's startup code in global.asax.cs one for each CallbackHandler based service you create:

protected void Application_Start(object sender, EventArgs e)
{
    CallbackHandlerRouteHandler.RegisterRoutes<StockService>(RouteTable.Routes);
}

With this code in place you can now add RouteUrl properties to any of your service methods. For the HelloWorld method that doesn't make a ton of sense but here is what a routed clean URL might look like in definition:

[CallbackMethod(RouteUrl="stocks/HelloWorld/{name}")]
public string HelloWorld(string name)
{ 
    return "Hello " + name + ". Time is: " + DateTime.Now.ToString();
}

The same URL I previously used now becomes a bit shorter and more readable with:

http://localhost/WestWindWebAjax/HelloWorld/Rick

It's an easy way to create cleaner URLs and still get the same functionality.

Calling the Service with $.getJSON()

Since the result produced is JSON you can now easily consume this data using jQuery's getJSON method. First we need a couple of scripts - jquery.js and ww.jquery.js in the page:

<!DOCTYPE html>
<html>
<head>
    <link href="Css/Westwind.css" rel="stylesheet" type="text/css" />
    <script src="scripts/jquery.min.js" type="text/javascript"></script>
    <script src="scripts/ww.jquery.min.js" type="text/javascript"></script>
</head>
<body>

Next let's add a small HelloWorld example form (what else) that has a single textbox to type a name, a button and a div tag to receive the result:

        <fieldset>
        <legend>Hello World</legend>
        
            Please enter a name: 
            <input type="text" name="txtHello" id="txtHello" value="" />
            <input type="button" id="btnSayHello" value="Say Hello (POST)"  />
            <input type="button" id="btnSayHelloGet" value="Say Hello (GET)"  />

            <div id="divHelloMessage" class="errordisplay" 
                 style="display:none;width: 450px;" >
            </div>

        </fieldset>

Then to call the HelloWorld method a little jQuery is used to hook the document startup and the button click followed by the $.getJSON call to retrieve the data from the server.

<script type="text/javascript">
    $(document).ready(function () {

        $("#btnSayHelloGet").click(function () {
            $.getJSON("SampleService.ashx",
                        { Method: "HelloWorld", name: $("#txtHello").val() },
                        function (result) {
                            $("#divHelloMessage")
                                    .text(result)
                                    .fadeIn(1000);
                        });

        });
</script>

.getJSON() expects a full URL to the endpoint of our service, which is the ASHX file. We can either provide a full URL (SampleService.ashx?Method=HelloWorld&name=Rick) or we can just provide the base URL and an object that encodes the query string parameters for us using an object map that has a property that matches each parameter for the server method. We can also use the clean URL routing syntax, but using the object parameter encoding actually is safer as the parameters will get properly encoded by jQuery.

The result returned is whatever the result on the server method is - in this case a string. The string is applied to the divHelloMessage element and we're done. Obviously this is a trivial example, but it demonstrates the basics of getting a JSON response back to the browser.

AJAX Post Syntax - using ajaxCallMethod()

The previous example allows you basic control over the data that you send to the server via querystring parameters. This works OK for simple values like short strings, numbers and boolean values, but doesn't really work if you need to pass something more complex like an object or an array back up to the server. To handle traditional RPC type messaging where the idea is to map server side functions and results to a client side invokation, POST operations can be used.

The easiest way to use this functionality is to use ww.jquery.js and the ajaxCallMethod() function. ww.jquery wraps jQuery's AJAX functions and knows implicitly how to call a CallbackServer method with parameters and parse the result.

Let's look at another simple example that posts a simple value but returns something more interesting. Let's start with the service method:

[CallbackMethod(RouteUrl="stocks/{symbol}")]
public StockQuote GetStockQuote(string symbol)
{
    Response.Cache.SetExpires(DateTime.UtcNow.Add(new TimeSpan(0, 2, 0)));

    StockServer server = new StockServer();
    var quote = server.GetStockQuote(symbol);
    if (quote == null)
        throw new ApplicationException("Invalid Symbol passed.");

    return quote;
}

This sample utilizes a small StockServer helper class (included in the sample) that downloads a stock quote from Yahoo's financial site via plain HTTP GET requests and formats it into a StockQuote object. Lets create a small HTML block that lets us query for the quote and display it:

<fieldset>
    <legend>Single Stock Quote</legend>

    Please enter a stock symbol:
    <input type="text" name="txtSymbol" id="txtSymbol" value="msft" />
    <input type="button" id="btnStockQuote" value="Get Quote" />

    <div id="divStockDisplay" class="errordisplay" style="display:none; width: 450px;">
        <div class="label-left">Company:</div>
        <div id="stockCompany"></div>
        <div class="label-left">Last Price:</div>
        <div id="stockLastPrice"></div>      
        <div class="label-left">Quote Time:</div>          
        <div id="stockQuoteTime"></div>
    </div>
</fieldset>

The final result looks something like this:

SingleStockQuote 

Let's hook up the button handler to fire the request and fill in the data as shown:

$("#btnStockQuote").click(function () {
    ajaxCallMethod("SampleService.ashx", "GetStockQuote",
                    [$("#txtSymbol").val()],
                    function (quote) {
                        $("#divStockDisplay").show().fadeIn(1000);
                        $("#stockCompany").text(quote.Company + " (" + quote.Symbol + ")");
                        $("#stockLastPrice").text(quote.LastPrice);
                        $("#stockQuoteTime").text(quote.LastQuoteTime.formatDate("MMM dd, HH:mm EST"));
                    }, onPageError);
});

So we point at SampleService.ashx and the GetStockQuote method, passing a single parameter of the input symbol value. Then there are two handlers for success and failure callbacks. 

The success handler is the interesting part - it receives the stock quote as a result and assigns its values to various 'holes' in the stock display elements.

The data that comes back over the wire is JSON and it looks like this:

{ "Symbol":"MSFT",
"Company":"Microsoft Corpora",
"OpenPrice":26.11,
"LastPrice":26.01,
"NetChange":0.02,
"LastQuoteTime":"2011-11-03T02:00:00Z",
"LastQuoteTimeString":"Nov. 11, 2011 4:20pm" }

which is an object representation of the data. JavaScript can evaluate this JSON string back into an object easily and that's the reslut that gets passed to the success function. The quote data is then applied to existing page content by manually selecting items and applying them. There are other ways to do this more elegantly like using templates, but here we're only interested in seeing how the data is returned. The data in the object is typed - LastPrice is a number and QuoteTime is a date.

Note about the date value: JavaScript doesn't have a date literal although the JSON embedded ISO string format used above  ("2011-11-03T02:00:00Z") is becoming fairly standard for JSON serializers. However, JSON parsers don't deserialize dates by default and return them by string. This is why the StockQuote actually returns a string value of LastQuoteTimeString for the same date. ajaxMethodCallback always converts dates properly into 'real' dates and the example above uses the real date value along with a .formatDate() data extension (also in ww.jquery.js) to display the raw date properly.

Errors and Exceptions

So what happens if your code fails? For example if I pass an invalid stock symbol to the GetStockQuote() method you notice that the code does this:

if (quote == null) throw new ApplicationException("Invalid Symbol passed.");

CallbackHandler automatically pushes the exception message back to the client so it's easy to pick up the error message. Regardless of what kind of error occurs: Server side, client side, protocol errors - any error will fire the failure handler with an error object parameter. The error is returned to the client via a JSON response in the error callback. In the previous examples I called onPageError which is a generic routine in ww.jquery that displays a status message on the bottom of the screen. But of course you can also take over the error handling yourself:

$("#btnStockQuote").click(function () {
    ajaxCallMethod("SampleService.ashx", "GetStockQuote",
                    [$("#txtSymbol").val()],
                    function (quote) {
                        $("#divStockDisplay").fadeIn(1000);
                        $("#stockCompany").text(quote.Company + " (" + quote.Symbol + ")");
                        $("#stockLastPrice").text(quote.LastPrice);
                        $("#stockQuoteTime").text(quote.LastQuoteTime.formatDate("MMM dd, hh:mmt"));
                    }, 
function (error, xhr) { $("#divErrorDisplay").text(error.message).fadeIn(1000); }); });

The error object has a isCallbackError, message and  stackTrace properties, the latter of which is only populated when running in Debug mode, and this object is returned for all errors: Client side, transport and server side errors. Regardless of which type of error you get the same object passed (as well as the XHR instance optionally) which makes for a consistent error retrieval mechanism.

Specifying HttpVerbs

You can also specify HTTP Verbs that are allowed using the AllowedHttpVerbs option on the CallbackMethod attribute:

[CallbackMethod(AllowedHttpVerbs=HttpVerbs.GET | HttpVerbs.POST)]
public string HelloWorld(string name)  { … }

If you're building REST style API's this might be useful to force certain request semantics onto the client calling. For the above if call with a non-allowed HttpVerb the request returns a 405 error response along with a JSON (or XML) error object result. The default behavior is to allow all verbs access (HttpVerbs.All).

Passing in object Parameters

Up to now the parameters I passed were very simple. But what if you need to send something more complex like an object or an array? Let's look at another example now that passes an object from the client to the server. Keeping with the Stock theme here lets add a method called BuyOrder that lets us buy some shares for a stock.

Consider the following service method that receives an StockBuyOrder object as a parameter:

[CallbackMethod]
public string BuyStock(StockBuyOrder buyOrder)
{
    var server = new StockServer();
    var quote = server.GetStockQuote(buyOrder.Symbol);
    if (quote == null)
        throw new ApplicationException("Invalid or missing stock symbol.");

    return string.Format("You're buying {0} shares of {1} ({2}) stock at {3} for a total of {4} on {5}.",
                         buyOrder.Quantity,
                         quote.Company,
                         quote.Symbol,
                         quote.LastPrice.ToString("c"),                                 
                         (quote.LastPrice * buyOrder.Quantity).ToString("c"),
                         buyOrder.BuyOn.ToString("MMM d"));
}

public class StockBuyOrder
{
    public string Symbol { get; set; }
    public int Quantity { get; set; }
    public DateTime BuyOn { get; set; }

    public StockBuyOrder()
    {
        BuyOn = DateTime.Now;
    }
}

This is a contrived do-nothing example that simply echoes back what was passed in, but it demonstrates how you can pass complex data to a callback method.

On the client side we now have a very simple form that captures the three values on a form:

<fieldset>
    <legend>Post a Stock Buy Order</legend>

    Enter a symbol: <input type="text" name="txtBuySymbol" id="txtBuySymbol" value="GLD" />&nbsp;&nbsp;
    Qty: <input type="text" name="txtBuyQty" id="txtBuyQty" value="10"  style="width: 50px" />&nbsp;&nbsp;
    Buy on: <input type="text" name="txtBuyOn" id="txtBuyOn" value="<%= DateTime.Now.ToString("d") %>" style="width: 70px;" />
    <input type="button" id="btnBuyStock" value="Buy Stock"  />

    <div id="divStockBuyMessage" class="errordisplay" style="display:none"></div>
</fieldset>

The completed form and demo then looks something like this:

BuyStockSample 

The client side code that picks up the input values and assigns them to object properties and sends the AJAX request looks like this:

$("#btnBuyStock").click(function () {
    // create an object map that matches StockBuyOrder signature
    var buyOrder =
    {
        Symbol: $("#txtBuySymbol").val(),
        Quantity: $("#txtBuyQty").val() * 1,  // number
        Entered: new Date()
    }
               
    ajaxCallMethod("SampleService.ashx", "BuyStock",
                        [buyOrder],
                        function (result) {
                            $("#divStockBuyMessage").text(result).fadeIn(1000);
                        }, onPageError);

});

The code creates an object and attaches the properties that match the server side object passed to the BuyStock method. Each property that you want to update needs to be included and the type must match (ie. string, number, date in this case). Any missing properties will not be set but also not cause any errors.

Pass POST data instead of Objects

In the last example I collected a bunch of values from form variables and stuffed them into object variables in JavaScript code. While that works, often times this isn't really helping - I end up converting my types on the client and then doing another conversion on the server. If lots of input controls are on a page and you just want to pick up the values on the server via plain POST variables - that can be done too - and it makes sense especially if you're creating and filling the client side object only to push data to the server.

Let's add another method to the server that once again lets us buy a stock. But this time let's not accept a parameter but rather send POST data to the server. Here's the server method receiving POST data:

[CallbackMethod]
public string BuyStockPost()
{
    StockBuyOrder buyOrder = new StockBuyOrder();

    buyOrder.Symbol = Request.Form["txtBuySymbol"]; ;
    int qty;
    int.TryParse(Request.Form["txtBuyQuantity"], out qty);
    buyOrder.Quantity = qty;
    DateTime time;
    DateTime.TryParse(Request.Form["txtBuyBuyOn"], out time);
    buyOrder.BuyOn = time;

    // Or easier way yet                        
    //FormVariableBinder.Unbind(buyOrder,null,"txtBuy");

    var server = new StockServer();
    var quote = server.GetStockQuote(buyOrder.Symbol);
    if (quote == null)
        throw new ApplicationException("Invalid or missing stock symbol.");


    return string.Format("You're buying {0} shares of {1} ({2}) stock at {3} for a total of {4} on {5}.",
                         buyOrder.Quantity,
                         quote.Company,
                         quote.Symbol,
                         quote.LastPrice.ToString("c"),
                         (quote.LastPrice * buyOrder.Quantity).ToString("c"),
                         buyOrder.BuyOn.ToString("MMM d"));
}

Clearly we've made this server method take more code than it did with the object parameter. We've basically moved the parameter assignment logic from the client to the server. As a result the client code to call this method is now a bit shorter since there's no client side shuffling of values from the controls to an object.

$("#btnBuyStockPost").click(function () {
    ajaxCallMethod("SampleService.ashx", "BuyStockPost",
    [],  // Note: No parameters -
    function (result) {
        $("#divStockBuyMessage").text(result).fadeIn(1000);
    }, onPageError, 
    // Force all page Form Variables to be posted
    { postbackMode: "Post" });
});

The client simply calls the BuyStockQuote method and pushes all the form variables from the page up to the server which parses them instead. The feature that makes this work is one of the options you can pass to the ajaxCallMethod() function:

{ postbackMode: "Post" });

which directs the function to include form variable POST data when making the service call. Other options include PostNoViewState (for WebForms to strip out WebForms crap vars), PostParametersOnly (default), None. If you pass parameters those are always posted to the server except when None is set.

The above code can be simplified a bit by using the FormVariableBinder helper, which can unbind form variables directly into an object:

FormVariableBinder.Unbind(buyOrder,null,"txtBuy");

which replaces the manual Request.Form[] reading code. It receives the object to unbind into, a string of properties to skip, and an optional prefix which is stripped off form variables to match property names. The component is similar to the MVC model binder but it's independent of MVC.

Returning non-JSON Data

CallbackHandler also supports returning non-JSON/XML data via special return types. You can return raw non-JSON encoded strings like this:

[CallbackMethod(ReturnAsRawString=true,ContentType="text/plain")]
public string HelloWorldNoJSON(string name)
{
    return "Hello " + name + ". Time is: " + DateTime.Now.ToString();
}

Calling this method results in just a plain string - no JSON encoding with quotes around the result. This can be useful if your server handling code needs to return a string or HTML result that doesn't fit well for a page or other UI component. Any string output can be returned.

You can also return binary data. Stream, byte[] and Bitmap/Image results are automatically streamed back to the client. Notice that you should set the ContentType of the request either on the CallbackMethod attribute or using Response.ContentType. This ensures the Web Server knows how to display your binary response. Using a stream response makes it possible to return any of data.

Streamed data can be pretty handy to return bitmap data from a method. The following is a method that returns a stock history graph for a particular stock over a provided number of years:

[CallbackMethod(ContentType="image/png",RouteUrl="stocks/history/graph/{symbol}/{years}")]
public Stream GetStockHistoryGraph(string symbol, int years = 2,int width = 500, int height=350)
{
    if (width == 0)
        width = 500;
    if (height == 0)
        height = 350;
    StockServer server = new StockServer();
    return server.GetStockHistoryGraph(symbol,"Stock History for " + symbol,width,height,years);
}

I can now hook this up into the JavaScript code when I get a stock quote. At the end of the process I can assign the URL to the service that returns the image into the src property and so force the image to display. Here's the changed code:

$("#btnStockQuote").click(function () {
    var symbol = $("#txtSymbol").val();
    ajaxCallMethod("SampleService.ashx", "GetStockQuote",
                    [symbol],
                    function (quote) {
                        $("#divStockDisplay").fadeIn(1000);
                        $("#stockCompany").text(quote.Company + " (" + quote.Symbol + ")");
                        $("#stockLastPrice").text(quote.LastPrice);
                        $("#stockQuoteTime").text(quote.LastQuoteTime.formatDate("MMM dd, hh:mmt"));

                        // display a stock chart
                        $("#imgStockHistory").attr("src", "stocks/history/graph/" + symbol + "/2");
                    },onPageError);
});

The resulting output then looks like this:

ImageDisplayFromService

The charting code uses the new ASP.NET 4.0 Chart components via code to display a bar chart of the 2 year stock data as part of the StockServer class which you can find in the sample download.

The ability to return arbitrary data from a service is useful as you can see - in this case the chart is clearly associated with the service and it's nice that the graph generation can happen off a handler rather than through a page. Images are common resources, but output can also be PDF reports, zip files for downloads etc. which is becoming increasingly more common to be returned from REST endpoints and other applications.

Why reinvent?

Obviously the examples I've shown here are pretty basic in terms of functionality. But I hope they demonstrate the core features of AJAX callbacks that you need to work through in most applications which is simple: return data, send back data and potentially retrieve data in various formats.

While there are other solutions when it comes down to making AJAX callbacks and servicing REST like requests, I like the flexibility my home grown solution provides. Simply put it's still the easiest solution that I've found that addresses my common use cases:

  • AJAX JSON RPC style callbacks
  • Url based access
  • XML and JSON Output from single method endpoint
  • XML and JSON POST support, querystring input, routing parameter mapping
  • UrlEncoded POST data support on callbacks
  • Ability to return stream/raw string data
  • Essentially ability to return ANYTHING from Service and pass anything

All these features are available in various solutions but not together in one place. I've been using this code base for over 4 years now in a number of projects both for myself and commercial work and it's served me extremely well. Besides the AJAX functionality CallbackHandler provides, it's also an easy way to create any kind of output endpoint I need to create. Need to create a few simple routines that spit back some data, but don't want to create a Page or View or full blown handler for it? Create a CallbackHandler and add a method or multiple methods and you have your generic endpoints.  It's a quick and easy way to add small code pieces that are pretty efficient as they're running through a pretty small handler implementation. I can have this up and running in a couple of minutes literally without any setup and returning just about any kind of data.

Resources

Posted in ASP.NET  jQuery  AJAX  

The Voices of Reason


 

Don Demsak
November 03, 2011

# re: Using the West Wind Web Toolkit to set up AJAX and REST Services

Have you looked into the new WebAPI stack from Microsoft? You can get it at http://wcf.codeplex.com/. Don't let the WCF in the name fool you, it looks and feels nothing like WCF. They are building a complete REST stack, and have been seeking more community feedback on the stack.

Rick Strahl
November 03, 2011

# re: Using the West Wind Web Toolkit to set up AJAX and REST Services

@Don - yes I've been following WebApi closely actually. I'll have a similar post on it shortly. I think feature wise WebApi nails it pretty well although there are number of things that I don't like (DataContract Serializer, separate JsonValue class and a few other things). However, I think it's a big step in the right direction!

Still I also think that WebApi duplicates what you basically could do already from the ASP.NET stack (creating full featured Http access basically) on the server side. With raw ASP.NET you have access to just about everything from low level to high level and I suppose that is part of what appeals to me with my solution. Most folks who end up doing Callbacks and REST APIs are already building Web apps and using the same stack and so are fairly familiar with it without having to embrace another API.

The only big advantage of WebApi I see is that you can host it outside of IIS which can be useful, but frankly is not that important to me or anybody I work with.

I have to take another look though - it's been a while since I've played with WebApi extensively and I definitely like what they're doing with the client side as well - .NET really needs that part because native HTTP support currenty is pretty basic.

Dan
November 04, 2011

# re: Using the West Wind Web Toolkit to set up AJAX and REST Services

once again, a very nice job. I've been at this for 10 years now and it seems that you teach me something new every month!

Jesper Liljegren
November 04, 2011

# re: Using the West Wind Web Toolkit to set up AJAX and REST Services

Hello Rick!

Quick question, how can I define in my Handler if the method should only accept POST, or GET?

Rick Strahl
November 04, 2011

# re: Using the West Wind Web Toolkit to set up AJAX and REST Services

@Jesper - you can capture the HttpMethod and based on that return a status code:

if (Request.HttpMethod != "POST")
{
    Response.StatusCode = HttpStatusCode.NotAllowed; // 405
    Response.StatusDescription = "Not Allowed";
    return null;  // must still return a result here!
}


or if you want to just return an error:


if (Request.HttpMethod != "POST")
    throw new UnauthorizedAccessException("Request must be accessed with POST");


which returns an error response (as a 500 result unless you override the StatusCode) to the client.

Rick Strahl
November 04, 2011

# re: Using the West Wind Web Toolkit to set up AJAX and REST Services

@Jesper - I also added a new attribute option: AllowedHttpVerbs to the CallbackHandler attribute. You can now do:

[CallbackMethod(RouteUrl="stocks/{symbol}",
                AllowedHttpVerbs=HttpVerbs.GET | HttpVerbs.POST)]
public StockQuote GetStockQuote(string symbol)
{ ... }


and it will return a HTTP 405 - Not allowed response if the wrong HTTP Verb is used. There's also another small tweak: Errors now will respect custom Http Status codes you set in code and not just return 500. So you can now do:

if (File.Exists(resourcePath)
{
   Response.StatusCode = HttpStatusCode.MethodNotAllowed;  // 405
   Response.StatusDescription = "Not Found - Resource not found";
   throw new ApplicationException("My Custom Error Message");
}

which results in a 405 result, but also an error object response.

Code's checked into the Subversion Repository and can be retrieved from there - it'll be added to the next release.

Ryan Keeter
November 07, 2011

# re: Using the West Wind Web Toolkit to set up AJAX and REST Services

At first, I was blown away by the lack of plumbing. It was all just so...easy. Then, when you returned an image and called the method requesting the image by merely setting the src attribute on an image from the client side...that kinda blew my mind. I have seen strings get shuttled around in my own code and all over the internet, but this thing passes back ANYTHING.

Well played sir, well played.

Rick Strahl
November 08, 2011

# re: Using the West Wind Web Toolkit to set up AJAX and REST Services

@Ryan - Yes that's the idea. You should be able to return just about anything easily. I frequently use this as a generic endpoint handler for an application unrelated to services - almost every app has something like an Image service or an upload endpoint that doesn't fit into pages and this setup is perfect for that!

But I can't take credit for the 'return anything' format - WCF REST also supports that and that's where I got the idea originally (as well as the RouteUrls support). To me this is the best pieces in one place - of course I might be just a little biased :-)

Jesper Liljegren
November 10, 2011

# re: Using the West Wind Web Toolkit to set up AJAX and REST Services

Hello Rick!

Awesome with the adding of HttpVerbs :)

But I ran into some problems when returning a TreeNode-type which is a class I created.
public class TreeNode
{
   public int Id;
   public string Description;
   public int Parent;
   public int Level;
   public List<TreeNode> Childs;
}


In the .ashx-file I see that the TreeNode contains the correct data. But when I get the return on the client side, all I get is an empty json-object

This is how the method looks in my .ashx-file

<CallbackMethod(RouteUrl:="GetRootNode/{asTree}")>
Public Function GetSearchAreas(ByVal asTree As Boolean) As TreeNode
   ' Do stuff to get the TreeNode
End Function


And this is how I call it
http://localhost:3461/GetRootNode/true


Best regards
Jesper

Rick Strahl
November 10, 2011

# re: Using the West Wind Web Toolkit to set up AJAX and REST Services

@Jesper - the default serializer only works with properties not fields. So if you promote your TreeNode members to properties it will work:

public class TreeNode
{
    public int Id {get; set; }
    public string Description {get; set; }
    public int Parent {get; set; }
    public int Level {get; set; }
    public List<TreeNode> Childs { get; set; }
}


Another option is that you can use another JSON serializer. By default the toolkit uses a custom JSON serializer, but you can also plug in the ASP.NET JavaScript serializer or JSON.NET (with some additional options).

In your Application_Start (or similar you can do):

JSONSerializer.DefaultJsonParserType = SupportedJsonParserTypes.JavaScriptSerializer;


which switches the JSON parser globally to the ASP.NET JavaScript serializer which does work with fields.

Finally, I also just added another flag to the class:

JSONSerializer.SerializeFields = true;


which you can also set in Application_Start. Once set it will make the default parser serialize properties as well. Code checked into the repository.

West Wind  © Rick Strahl, West Wind Technologies, 2005 - 2024