<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Encosia &#187; ASMX Mistakes and Misconceptions</title>
	<atom:link href="http://encosia.com/category/asmx-mistakes-and-misconceptions/feed/" rel="self" type="application/rss+xml" />
	<link>http://encosia.com</link>
	<description>ASP.NET and AJAX code, ideas, and examples.</description>
	<lastBuildDate>Sun, 29 Apr 2012 21:35:22 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<item>
		<title>ASP.NET web services mistake: manual JSON serialization</title>
		<link>http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/</link>
		<comments>http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/#comments</comments>
		<pubDate>Wed, 13 Apr 2011 17:16:41 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[ASMX Mistakes and Misconceptions]]></category>
		<category><![CDATA[ASP.NET]]></category>

		<guid isPermaLink="false">http://encosia.com/?p=1106</guid>
		<description><![CDATA[If you’ve spent much time working with the .NET platform, ASP.NET&#8217;s simple, convention-based approach to exposing JSON endpoints seems just about too good to be true. After years of fiddling with manual settings in XML configuration files, it&#8217;s understandable to assume that working with JSON in ASP.NET would require a similar rigmarole, yet it does [...]
Related posts:<ol>
<li><a href='http://encosia.com/asmx-scriptservice-mistake-invalid-json-primitive/' rel='bookmark' title='ASMX ScriptService mistake &#8211; Invalid JSON primitive'>ASMX ScriptService mistake &#8211; Invalid JSON primitive</a></li>
<li><a href='http://encosia.com/using-jquery-to-consume-aspnet-json-web-services/' rel='bookmark' title='Using jQuery to Consume ASP.NET JSON Web Services'>Using jQuery to Consume ASP.NET JSON Web Services</a></li>
<li><a href='http://encosia.com/using-complex-types-to-make-calling-services-less-complex/' rel='bookmark' title='Using complex types to make calling services less&#8230; complex'>Using complex types to make calling services less&#8230; complex</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>If you’ve spent much time working with the .NET platform, ASP.NET&#8217;s simple, convention-based approach to exposing JSON endpoints seems just about too good to be true. After years of fiddling with manual settings in XML configuration files, it&#8217;s understandable to assume that working with JSON in ASP.NET would require a similar rigmarole, yet it does not.</p>
<p>Unfortunately, this unexpected ease-of-use isn’t obvious if you don’t already know about it, which has led some developers to build needlessly complicated solutions to problems that don&#8217;t actually exist. In this post, I want to point out a few ways <strong>not</strong> to approach JSON in ASP.NET and then show you a couple examples of leveraging the frame work to do it &#8220;right&#8221;.</p>
<h3>A couple examples of what NOT to do</h3>
<p>To show you exactly what I&#8217;m talking about, let&#8217;s start by looking at a few concrete examples of ways that you should <strong>not</strong> handle sending and receiving JSON in your ASP.NET services.</p>
<p>For all the examples, we&#8217;re going to be trying to send and/or receive instances of this Person class:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Person
<span style="color: #000000;">&#123;</span>
  <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> FirstName <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
  <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> LastName <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Once you progress beyond simple scalar types, sending objects (and collections of them) back and forth is a pretty logical next step, and that&#8217;s also the point where this manual serialization trouble seems to begin. So, working with this simple Person class should serve as a realistic example, without being overly complex.</p>
<h4>Manual serialization, using JavaScriptSerializer</h4>
<p>The most common variant of this mistake that I&#8217;ve seen is using JavaScriptSerializer to manually build a JSON string and then returning that string as the result of a service method. For example, if you didn&#8217;t know better, you might do this to return an instance of the Person class:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>ScriptService<span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> PersonService <span style="color: #008000;">:</span> WebService
<span style="color: #000000;">&#123;</span>
  <span style="color: #000000;">&#91;</span>WebMethod<span style="color: #000000;">&#93;</span>
  <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> GetDave<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
  <span style="color: #000000;">&#123;</span>
    Person dave <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Person<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    dave.<span style="color: #0000FF;">FirstName</span> <span style="color: #008000;">=</span> Dave<span style="color: #008000;">;</span>
    dave.<span style="color: #0000FF;">LastName</span> <span style="color: #008000;">=</span> Ward<span style="color: #008000;">;</span>
&nbsp;
    JavaScriptSerializer jss <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> JavaScriptSerializer<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// Results in {&quot;FirstName&quot;:&quot;Dave&quot;,&quot;LastName&quot;:&quot;Ward&quot;}</span>
    <span style="color: #FF0000;">string</span> json <span style="color: #008000;">=</span> jss.<span style="color: #0000FF;">Serialize</span><span style="color: #008000;">&lt;</span>Person<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>dave<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">return</span> json<span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>This may look sensible enough on the surface. After all, the <code>json</code> variable does end up containing a nicely serialized JSON string, which seems to be what we want.  However, <strong>you should not do this</strong>.</p>
<h4>What actually happens</h4>
<p>Part of the beauty of using ASP.NET&#8217;s JSON-enabled services is that you rarely have to think much about the translation between JSON on the client-side and .NET objects on the server-side.  When requested with the proper incantations, <strong>ASP.NET automatically JSON serializes your service methods&#8217; responses, even if their result is an object or collection of objects</strong>.</p>
<p>Unfortunately, that automatic translation also makes it easy to end up with doubly-serialized responses if you aren&#8217;t aware that ASP.NET is already handling the serialization for you, which is exactly what would happen in the preceding example. The end result is that the Person object is serialized twice before it gets back to the browser &#8211; once as part of the method&#8217;s imperative code and then a second time by convention.</p>
<p>In other words, it&#8217;s understandable to expect the previous code example would return this response:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#123;</span><span style="color: #3366CC;">&quot;FirstName&quot;</span><span style="color: #339933;">:</span><span style="color: #3366CC;">&quot;Dave&quot;</span><span style="color: #339933;">,</span><span style="color: #3366CC;">&quot;LastName&quot;</span><span style="color: #339933;">:</span><span style="color: #3366CC;">&quot;Ward&quot;</span><span style="color: #009900;">&#125;</span></pre></div></div>

<p>But, what it actually returns is this:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// All the quotes in the manually generated JSON must be escaped in </span>
<span style="color: #006600; font-style: italic;">//  the second pass, hence all the backslashes.</span>
<span style="color: #009900;">&#123;</span><span style="color: #3366CC;">&quot;d&quot;</span><span style="color: #339933;">:</span><span style="color: #3366CC;">&quot;{<span style="color: #000099; font-weight: bold;">\&quot;</span>FirstName<span style="color: #000099; font-weight: bold;">\&quot;</span>:<span style="color: #000099; font-weight: bold;">\&quot;</span>Dave<span style="color: #000099; font-weight: bold;">\&quot;</span>,<span style="color: #000099; font-weight: bold;">\&quot;</span>LastName<span style="color: #000099; font-weight: bold;">\&quot;</span>:<span style="color: #000099; font-weight: bold;">\&quot;</span>Ward<span style="color: #000099; font-weight: bold;">\&quot;</span>}&quot;</span><span style="color: #009900;">&#125;</span></pre></div></div>

<p>What a mess. That’s probably not what you had in mind, is it?</p>
<h4>Using DataContractJsonSerializer or Json.NET is no better</h4>
<p>This may seem obvious, but I want to point out that using a different manual serialization tool, like WCF&#8217;s DataContractJsonSerializer or Json.NET, in place of JavaScriptSerializer above does not remedy the underlying problem. I only mention it because I&#8217;ve seen those variations of the mistake floating around too.</p>
<p>If anything, in the case of DataContractJsonSerializer, it&#8217;s even worse. DCJS&#8217; handling of Dictionary collections and Enums makes life unnecessarily tedious at times, and the code to manually invoke it is even more verbose than that for JavaScriptSerializer.</p>
<h3>The impact this mistake has on the client-side</h3>
<p>If it weren&#8217;t bad enough to add extra computational overhead on the server-side, cruft up the response with escaping backslashes, and increase the size of the JSON payload over the wire, this mistake carries a penalty on the client-side too.</p>
<p>Most JavaScript frameworks automatically deserialize JSON responses, but (rightfully) only expect one level of JSON serialization. That means that the standard functionality provided by most libraries will only unwrap one level of the doubly serialized stack of JSON produced by the previous example.</p>
<p>So, even after the response comes back and your framework has deserialized it once, you&#8217;ll still need to deserialize it a second time to finally extract a usable JavaScript object if you&#8217;ve made the mistake of manually serializing. For example, this is code you might see to mitigate that in jQuery:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$.<span style="color: #660066;">ajax</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
  type<span style="color: #339933;">:</span> <span style="color: #3366CC;">'POST'</span><span style="color: #339933;">,</span>
  dataType<span style="color: #339933;">:</span> <span style="color: #3366CC;">'json'</span><span style="color: #339933;">,</span>
  contentType<span style="color: #339933;">:</span> <span style="color: #3366CC;">'application/json'</span><span style="color: #339933;">,</span>
  url<span style="color: #339933;">:</span> <span style="color: #3366CC;">'PersonService.asmx/GetDave'</span><span style="color: #339933;">,</span>
  data<span style="color: #339933;">:</span> <span style="color: #3366CC;">'{}'</span><span style="color: #339933;">,</span>
  success<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>response<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #006600; font-style: italic;">// At this point, response is a *string* containing the</span>
    <span style="color: #006600; font-style: italic;">//  manually generated JSON, and must be deserialized again.</span>
&nbsp;
    <span style="color: #003366; font-weight: bold;">var</span> person<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #006600; font-style: italic;">// This is a very common way of handling</span>
    <span style="color: #006600; font-style: italic;">//  the second round of JSON deserialization:</span>
    person <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">eval</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'('</span> <span style="color: #339933;">+</span> response <span style="color: #339933;">+</span> <span style="color: #3366CC;">')'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #006600; font-style: italic;">// You'll also see this approach, which</span>
    <span style="color: #006600; font-style: italic;">//  uses browser-native JSON handling:</span>
    person <span style="color: #339933;">=</span> JSON.<span style="color: #660066;">parse</span><span style="color: #009900;">&#40;</span>response<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #006600; font-style: italic;">// Using a framework's built-in helper </span>
    <span style="color: #006600; font-style: italic;">//  method is another common fix:</span>
    person <span style="color: #339933;">=</span> $.<span style="color: #660066;">parseJSON</span><span style="color: #009900;">&#40;</span>person<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Regardless of which approach is used, if you see code like this running after the framework has already processed a response, it&#8217;s a pretty good indication that something is wrong. Not only is this more complicated and verbose than it needs to be, but it adds additional overhead on the client-side for absolutely no valid reason.</p>
<h3>Flipping the script (and the JSON)</h3>
<p>Redundant JSON serialization on responses is definitely one of the most common variations of this problem I&#8217;ve seen, but the inverse of that mistake also seems to be an alluring pitfall. Far too often, I’ve seen service methods that accept a single JSON string as their input parameter and then manually parse several intended inputs from that.</p>
<p>Something like this to accept a Person object form the client-side and save it on the server-side, for example:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>ScriptService<span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> PersonService <span style="color: #008000;">:</span> WebService
<span style="color: #000000;">&#123;</span>
  <span style="color: #000000;">&#91;</span>WebMethod<span style="color: #000000;">&#93;</span>
  <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> SavePerson<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> PersonToSave<span style="color: #000000;">&#41;</span>
  <span style="color: #000000;">&#123;</span>
    JavaScriptSerializer jss <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> JavaScriptSerializer<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    Person p <span style="color: #008000;">=</span> jss.<span style="color: #0000FF;">Deserialize</span><span style="color: #008000;">&lt;</span>Person<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>PersonToSave<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    p.<span style="color: #0000FF;">Save</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Just as ASP.NET automatically JSON serializes responses on its JSON-friendly services, it also expects that the input parameters will be in JSON format and automatically deserializes those on the way in. So, in reverse order, the approach above makes a mistake similar to the ones shown earlier.</p>
<p>To make this work, we&#8217;d need to pass in JSON that looks something like this, obfuscating the actually desired input parameters inside a single, doubly-serialized string parameter.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#123;</span><span style="color: #3366CC;">&quot;PersonToSave&quot;</span><span style="color: #339933;">:</span><span style="color: #3366CC;">&quot;{<span style="color: #000099; font-weight: bold;">\&quot;</span>FirstName<span style="color: #000099; font-weight: bold;">\&quot;</span>:<span style="color: #000099; font-weight: bold;">\&quot;</span>Dave<span style="color: #000099; font-weight: bold;">\&quot;</span>,<span style="color: #000099; font-weight: bold;">\&quot;</span>LastName<span style="color: #000099; font-weight: bold;">\&quot;</span>:<span style="color: #000099; font-weight: bold;">\&quot;</span>Ward<span style="color: #000099; font-weight: bold;">\&quot;</span>}&quot;</span><span style="color: #009900;">&#125;</span></pre></div></div>

<p>Through the convenience of JSON.stringify(), it&#8217;s not even terribly hard to stumble onto a process for cobbling that double-JSON structure together on the client-side and making this approach work.  I strongly recommend against it though.  Even if the double-JSON didn&#8217;t carry extra overhead in several aspects, having a single input parameter of type string on this method is misleading.  A year from now, will anyone realize what type of parameter that method accepts without looking down into the manual parsing code?  Probably not.</p>
<h3>Doing it right</h3>
<p>Briefly, here are what I suggest as better ways to handle passing our Person object in and out of ASP.NET services.</p>
<h4>Returning an object</h4>
<p>Returning a .NET object from ASP.NET services is incredibly easy. If you let go and just trust the service to handle JSON translation for you, &#8220;it just works&#8221;:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>ScriptService<span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> PersonService <span style="color: #008000;">:</span> WebService
<span style="color: #000000;">&#123;</span>
  <span style="color: #000000;">&#91;</span>WebMethod<span style="color: #000000;">&#93;</span>
  <span style="color: #0600FF;">public</span> Person GetDave<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
  <span style="color: #000000;">&#123;</span>
    Person dave <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Person<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    dave.<span style="color: #0000FF;">FirstName</span> <span style="color: #008000;">=</span> Dave<span style="color: #008000;">;</span>
    dave.<span style="color: #0000FF;">LastName</span> <span style="color: #008000;">=</span> Ward<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// So easy!</span>
    <span style="color: #0600FF;">return</span> dave<span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>As long as you call that service method through a ScriptManager&#8217;s service proxy or u<a href="http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/">sing the correct parameters when using a library like jQuery</a>, ASP.NET will automatically serialize the Person object and return it as raw, unencumbered JSON.</p>
<h4>Accepting an object from the client-side</h4>
<p>Accepting a Person object from the client-side works identically, in reverse. ASP.NET does a great job of matching JSON-serialized request parameters to .NET&#8217;s types, collections, and even your own custom objects.</p>
<p>For example this is how you could accept a Person object, which would even then allow you to call that object&#8217;s custom methods:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>ScriptService<span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> PersonService <span style="color: #008000;">:</span> WebService
<span style="color: #000000;">&#123;</span>
  <span style="color: #000000;">&#91;</span>WebMethod<span style="color: #000000;">&#93;</span>
  <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> SavePerson<span style="color: #000000;">&#40;</span>Person PersonToSave<span style="color: #000000;">&#41;</span>
  <span style="color: #000000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// No, really, that's it (assuming Person has a Save() method).</span>
    PersonToSave.<span style="color: #0000FF;">Save</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>For more information about how to implement this on both server- and client-side, I recommend reading my old, but still-relevant, post about <a href="http://encosia.com/2009/04/07/using-complex-types-to-make-calling-services-less-complex/">using objects to simplify calling ASP.NET services</a>.</p>
<h3>My request to you</h3>
<p>I don&#8217;t know where the manual [de]serialization approach is coming from, but it seems to be gaining traction lately based on what I&#8217;ve seen on Stack Overflow and the ASP.NET forums.  I must assume there are tutorials out there with sample code showing that approach, or valid approaches within ASHX handlers are being mistaken for the proper solution across the board.</p>
<p>Whatever the source, I can only find and correct a fraction of the postings and questions containing this mistake myself.  If you notice an instance of these mistakes that has not been corrected, please take a moment and point them toward this post.</p>
<p>Together, hopefully we can stop the spread of this particular mistake.</p>
<p>Related posts:<ol>
<li><a href='http://encosia.com/asmx-scriptservice-mistake-invalid-json-primitive/' rel='bookmark' title='ASMX ScriptService mistake &#8211; Invalid JSON primitive'>ASMX ScriptService mistake &#8211; Invalid JSON primitive</a></li>
<li><a href='http://encosia.com/using-jquery-to-consume-aspnet-json-web-services/' rel='bookmark' title='Using jQuery to Consume ASP.NET JSON Web Services'>Using jQuery to Consume ASP.NET JSON Web Services</a></li>
<li><a href='http://encosia.com/using-complex-types-to-make-calling-services-less-complex/' rel='bookmark' title='Using complex types to make calling services less&#8230; complex'>Using complex types to make calling services less&#8230; complex</a></li>
</ol></p><hr />

<p>You've been reading <a href="http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/">ASP.NET web services mistake: manual JSON serialization</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p>

<p>If you've got any feedback, please click through and leave a comment; I'd love to hear from you. You can <a href="http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/#post-commentblock">click here to jump directly to the comment section of this post</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/feed/</wfw:commentRss>
		<slash:comments>89</slash:comments>
		</item>
		<item>
		<title>ASMX ScriptService mistake &#8211; Invalid JSON primitive</title>
		<link>http://encosia.com/asmx-scriptservice-mistake-invalid-json-primitive/</link>
		<comments>http://encosia.com/asmx-scriptservice-mistake-invalid-json-primitive/#comments</comments>
		<pubDate>Tue, 01 Jun 2010 04:33:58 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASMX Mistakes and Misconceptions]]></category>
		<category><![CDATA[ASP.NET]]></category>

		<guid isPermaLink="false">http://encosia.com/?p=998</guid>
		<description><![CDATA[One group of searches that consistently brings traffic here is variations on the error: Invalid JSON primitive. Unfortunately, the post that Google sends that traffic to doesn’t address the issue until somewhere within its 150+ comments. Today, the topic gets its own post. If you’ve worked with ASMX ScriptServices or Page Methods without ASP.NET AJAX&#8217;s [...]
Related posts:<ol>
<li><a href='http://encosia.com/asmx-scriptservice-mistakes-installation-and-configuration/' rel='bookmark' title='ASMX ScriptService mistake: Installation and configuration'>ASMX ScriptService mistake: Installation and configuration</a></li>
<li><a href='http://encosia.com/asmx-and-json-common-mistakes-and-misconceptions/' rel='bookmark' title='ASMX and JSON &ndash; Common mistakes and misconceptions'>ASMX and JSON &ndash; Common mistakes and misconceptions</a></li>
<li><a href='http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/' rel='bookmark' title='ASP.NET web services mistake: manual JSON serialization'>ASP.NET web services mistake: manual JSON serialization</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>One group of searches that consistently brings traffic here is variations on the error: <strong>Invalid JSON primitive</strong>. Unfortunately, the post that Google sends that traffic to doesn’t address the issue until somewhere within its 150+ comments.</p>
<p>Today, the topic gets its own post.</p>
<p>If you’ve worked with ASMX ScriptServices or Page Methods without ASP.NET AJAX&#8217;s client-side proxy (e.g. using jQuery or pure XMLHttpRequest code), you’ve may have seen this cryptic error yourself. Or, perhaps you’ve just arrived here due to seeing it for the first time.</p>
<p>Either way, you may be surprised to learn that <strong>the most common reason for this error is that you’ve lied to ASP.NET</strong> during your AJAX request.</p>
<h3>It all begins with the Content-Type</h3>
<p>HTTP’s <a href="http://www.w3.org/Protocols/rfc1341/4_Content-Type.html" rel="nofollow" target="_blank">Content-Type</a> header is a fundamental aspect of communication between browsers and servers, yet often remains hidden from us in day-to-day development. <strong>The Content-Type header allows an HTTP connection to describe the format of its contents</strong>, using <a href="http://en.wikipedia.org/wiki/Internet_media_type" rel="nofollow" target="_blank">Internet media types</a> (also known as MIME types). A few common ones that you&#8217;ve probably seen before are <em>text/html</em>, <em>image/png</em>, and the more topical <em>application/json</em>.</p>
<p>Without the flexible negotiation process content types provide, your users’ browsers and your version of IIS would have to both be “ASMX Compatible” and “JSON Compatible” in order for ScriptServices to function. What a nightmare that would be! The IE6 difficulties we face today would pale in comparison.</p>
<p>Further, Content-Type negotiation is part of what allows a single URL, such as WebService.asmx, to represent data in more than one format (e.g. XML and JSON in ASMX’s case).</p>
<p>The benefits of Content-Type negotiation are well worth a bit of occasional hassle.</p>
<h3>Okay, but why does that matter?</h3>
<p>When your browser sends a POST request, the W3C&#8217;s recommendation is that it should default to using a Content-Type of <em>application/x-www-form-urlencoded</em>. <a href="http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1" rel="nofollow" target="_blank">The HTML 4.01 spec describes that serialization scheme</a>:</p>
<blockquote>
<p>This is the default content type. Forms submitted with this content type must be encoded as follows:</p>
<ol>
<li>[Omitted for brevity; not relevant to this post.] </li>
<li>The control names/values are listed in the order they appear in the document. <strong>The name is separated from the value by &#8216;=&#8217; and name/value pairs are separated from each other by &#8216;&amp;&#8217;.</strong> </li>
</ol>
</blockquote>
<p>For an example of what that means, consider this simple form:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;form</span> <span style="color: #000066;">method</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;post&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;label&gt;</span></span>First Name<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/label&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;input</span> <span style="color: #000066;">id</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;FirstName&quot;</span> <span style="color: #000066;">value</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;Dave&quot;</span> <span style="color: #000066;">name</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;FirstName&quot;</span> <span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;label&gt;</span></span>Last Name<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/label&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;input</span> <span style="color: #000066;">id</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;LastName&quot;</span> <span style="color: #000066;">value</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;Ward&quot;</span> <span style="color: #000066;">name</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;LastName&quot;</span> <span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/form&gt;</span></span></pre></div></div>

<p>When the preceding form is submitted with URL encoded serialization, the request’s POST data will look like this:</p>
<p><img title="URLEncoded POST data" alt="Firebug screenshot showing the URLEncoded POST data" src="http://encosia.com/blog/wp-content/uploads/2010/05/url-encoded-post-data.png" width="492" height="172" /></p>
<p>That standardized serialization format allows a server-side backend like ASP.NET to decipher a form submission’s contents and give you access to each key/value pair. Regardless of what sort of browser submits a form to the server, the Content-Type facilitates a predictable conversion from POST data to server-side collection.</p>
<p>In other words, <strong>the Content-Type corresponds to a serialization scheme</strong>.</p>
<h3>What does that have to do with JSON Primitives?</h3>
<p>Understanding Content-Type negotiation and how it relates to serialization is important due to its role in coaxing JSON out of ASMX ScriptServices. Specifically, the fact that <a href="http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/" target="_blank">you must set a Content-Type of application/json on the request</a><em></em> means <strong>you’re instructing ASP.NET to interpret your input parameters as JSON serialized data</strong>.</p>
<p>However, the W3C&#8217;s mandate of URL encoding by default means that most AJAX libraries default to that serialization scheme. Similarly, AJAX tutorials targeting endpoints other than ASMX ScriptServices (including even ASP.NET MVC examples) will describe sending URL encoded data to the server.</p>
<p>In other words, when you’re working with a client-side object like this:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> Person <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span> FirstName<span style="color: #339933;">:</span> <span style="color: #3366CC;">'Dave'</span><span style="color: #339933;">,</span> 
               LastName<span style="color: #339933;">:</span>  <span style="color: #3366CC;">'Ward'</span> <span style="color: #009900;">&#125;</span></pre></div></div>

<p>The default serialization scheme makes it easy to inadvertently transmit that data to the server as a URL encoded string:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">FirstName<span style="color: #339933;">=</span>Dave<span style="color: #339933;">&amp;</span>LastName<span style="color: #339933;">=</span>Ward</pre></div></div>

<p>Again, remember that <a target="_blank" href="http://weblogs.asp.net/scottgu/archive/2007/04/04/json-hijacking-and-how-asp-net-ajax-1-0-mitigates-these-attacks.aspx">a Content-Type of <em>application/json</em> is a requirement when working with ASMX ScriptServices</a>. By setting that Content-Type on the request, you’ve committed to sending JSON serialized parameters, and a URL encoded string is far from valid JSON.</p>
<p>In fact, it’s <strong>invalid JSON</strong> (primitive?), hence the cryptic error message.</p>
<p>Instead of the URL encoded string above, you must be sure to send a JSON string:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#123;</span><span style="color: #3366CC;">'FirstName'</span><span style="color: #339933;">:</span><span style="color: #3366CC;">'Dave'</span><span style="color: #339933;">,</span><span style="color: #3366CC;">'LastName'</span><span style="color: #339933;">:</span><span style="color: #3366CC;">'Ward'</span><span style="color: #009900;">&#125;</span></pre></div></div>

<p>Whether you&#8217;re using XMLHttpRequest directly or a JavaScript library that abstracts the details, getting your request&#8217;s serialization wrong is the root of the invalid JSON primitive error. However, a more specific issue tends to be the leading cause of this happening.</p>
<h3>When good JavaScript libraries go bad</h3>
<p>The most common source of this error stems from a subtlety of using jQuery’s $.ajax() method to call ASMX ScriptServices. Cobbling together snippets of code from the documentation, platform agnostic tutorials, and even posts here on my site, it’s easy to end up with something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// WRONG!</span>
$.<span style="color: #660066;">ajax</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
  type<span style="color: #339933;">:</span> <span style="color: #3366CC;">'POST'</span><span style="color: #339933;">,</span>
  contentType<span style="color: #339933;">:</span> <span style="color: #3366CC;">'application/json'</span><span style="color: #339933;">,</span>
  dataType<span style="color: #339933;">:</span> <span style="color: #3366CC;">'json'</span><span style="color: #339933;">,</span>
  url<span style="color: #339933;">:</span> <span style="color: #3366CC;">'WebService.asmx/Hello'</span><span style="color: #339933;">,</span>
  data<span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span> FirstName<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Dave&quot;</span><span style="color: #339933;">,</span> LastName<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Ward&quot;</span> <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Notice the JavaScript object literal being supplied to $.ajax()’s data parameter. That appears vaguely correct, but will result in the invalid JSON primitive error.</p>
<p>Why? <strong>jQuery serializes $.ajax()’s data parameter using the URL encoded scheme, regardless of what Content-Type is specified</strong>. Even though the contentType parameter clearly specifies JSON serialization, this URL encoded string is what jQuery will send to the server:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">FirstName<span style="color: #339933;">=</span>Dave<span style="color: #339933;">&amp;</span>LastName<span style="color: #339933;">=</span>Ward</pre></div></div>

<p>That obviously isn&#8217;t valid JSON!</p>
<p>The solution is as simple as two single-quotes:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// RIGHT</span>
$.<span style="color: #660066;">ajax</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
  type<span style="color: #339933;">:</span> <span style="color: #3366CC;">'POST'</span><span style="color: #339933;">,</span>
  contentType<span style="color: #339933;">:</span> <span style="color: #3366CC;">'application/json'</span><span style="color: #339933;">,</span>
  dataType<span style="color: #339933;">:</span> <span style="color: #3366CC;">'json'</span><span style="color: #339933;">,</span>
  url<span style="color: #339933;">:</span> <span style="color: #3366CC;">'WebService.asmx/Hello'</span><span style="color: #339933;">,</span>
  data<span style="color: #339933;">:</span> <span style="color: #3366CC;">'{ FirstName: &quot;Dave&quot;, LastName: &quot;Ward&quot; }'</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Did you spot the difference?</p>
<p>Instead of a JavaScript object literal, <strong>the data parameter is a JSON string now</strong>. <a href="http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/" target="_blank">The difference is subtle, but helpful to understand</a>. Since it’s a string, jQuery won’t attempt to perform any further transformation, and the JSON string will be unimpeded as it is passed to the ASMX ScriptService.</p>
<h3>It doesn’t have to be this way</h3>
<p>The problem is trivial once you’re aware of the underlying issue, but there’s not a great reason I can see why things need to be this way in the first place. Either half of this equation could easily provide a remedy.</p>
<p><strong>jQuery</strong> – I believe the most correct solution would be $.ajax() attempting to honor the serialization scheme indicated by its contentType parameter. In the case of <em>application/json</em>, fixing this could be easy as testing for JSON.stringify and using it if available.  That would work great, but also avoid adding any complexity/size to jQuery core.</p>
<p>That would leave it our responsibility to reference a copy of json2.js in older browsers, but that convention wouldn’t be much of a burden. <a href="http://encosia.com/2009/04/07/using-complex-types-to-make-calling-services-less-complex/" target="_blank">We generally do that anyway when the client-side objects get complex</a>.</p>
<p><strong>Microsoft</strong> – It’s absolutely correct that the framework throws an error when you lie to it about what you’re sending. However, a bit of leniency could potentially save thousands of hours spent troubleshooting this problem (if my search traffic is any indication of its prevalence).</p>
<p>Is there any reason that the ScriptHandlerFactory can’t intelligently differentiate between between JSON and URL encoded inputs? If the first non-whitespace character of the request isn’t an opening curly brace, why not attempt to deserialize it as URL encoded before throwing an invalid JSON primitive error?</p>
<p>Related posts:<ol>
<li><a href='http://encosia.com/asmx-scriptservice-mistakes-installation-and-configuration/' rel='bookmark' title='ASMX ScriptService mistake: Installation and configuration'>ASMX ScriptService mistake: Installation and configuration</a></li>
<li><a href='http://encosia.com/asmx-and-json-common-mistakes-and-misconceptions/' rel='bookmark' title='ASMX and JSON &ndash; Common mistakes and misconceptions'>ASMX and JSON &ndash; Common mistakes and misconceptions</a></li>
<li><a href='http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/' rel='bookmark' title='ASP.NET web services mistake: manual JSON serialization'>ASP.NET web services mistake: manual JSON serialization</a></li>
</ol></p><hr />

<p>You've been reading <a href="http://encosia.com/asmx-scriptservice-mistake-invalid-json-primitive/">ASMX ScriptService mistake &#8211; Invalid JSON primitive</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p>

<p>If you've got any feedback, please click through and leave a comment; I'd love to hear from you. You can <a href="http://encosia.com/asmx-scriptservice-mistake-invalid-json-primitive/#post-commentblock">click here to jump directly to the comment section of this post</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/asmx-scriptservice-mistake-invalid-json-primitive/feed/</wfw:commentRss>
		<slash:comments>34</slash:comments>
		</item>
		<item>
		<title>ASMX ScriptService mistake: Installation and configuration</title>
		<link>http://encosia.com/asmx-scriptservice-mistakes-installation-and-configuration/</link>
		<comments>http://encosia.com/asmx-scriptservice-mistakes-installation-and-configuration/#comments</comments>
		<pubDate>Tue, 09 Mar 2010 03:29:07 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASMX Mistakes and Misconceptions]]></category>
		<category><![CDATA[ASP.NET]]></category>

		<guid isPermaLink="false">http://encosia.com/?p=972</guid>
		<description><![CDATA[Continuing my series of posts about ASMX services and JSON, in this post I’m going to cover two common mistakes that plague the process of getting a project’s first ASMX ScriptService working: Installing System.Web.Extensions into the GAC and configuring your web.config. System.Web.Extensions (aka ASP.NET AJAX) The ability for ASMX services to return raw JSON is [...]
Related posts:<ol>
<li><a href='http://encosia.com/asmx-scriptservice-mistake-invalid-json-primitive/' rel='bookmark' title='ASMX ScriptService mistake &#8211; Invalid JSON primitive'>ASMX ScriptService mistake &#8211; Invalid JSON primitive</a></li>
<li><a href='http://encosia.com/asmx-and-json-common-mistakes-and-misconceptions/' rel='bookmark' title='ASMX and JSON &ndash; Common mistakes and misconceptions'>ASMX and JSON &ndash; Common mistakes and misconceptions</a></li>
<li><a href='http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/' rel='bookmark' title='ASP.NET web services mistake: manual JSON serialization'>ASP.NET web services mistake: manual JSON serialization</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>Continuing <a href="http://encosia.com/2010/03/03/asmx-and-json-common-mistakes-and-misconceptions/">my series of posts about ASMX services and JSON</a>, in this post I’m going to cover two common mistakes that plague the process of getting a project’s first ASMX ScriptService working: <strong>Installing System.Web.Extensions</strong> into the GAC and <strong>configuring your web.config</strong>.</p>
<h3>System.Web.Extensions (aka ASP.NET AJAX)</h3>
<p>The ability for ASMX services to return raw JSON is made possible by two key features originally added by the ASP.NET AJAX Extensions v1.0:</p>
<ul>
<li><strong>JavaScriptSerializer</strong> – <a href="http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer(VS.100).aspx" target="_blank">The JavaScriptSerializer class</a> is the actual workhorse that translates back and forth between JSON strings and .NET CLR objects. Though less powerful than WCF’s DataContractJsonSerializer and third-party libraries like <a href="http://www.codeplex.com/Json" rel="nofollow" target="_blank">Json.NET</a>, JavaScriptSerializer is likely all you’ll ever need for simple AJAX callbacks. </li>
<li><strong>ScriptHandlerFactory</strong> – There are several more classes behind the scenes*, but the ScriptHandlerFactory is the tip of the iceberg that you&#8217;ll need to remember during configuration. Redirecting ASMX requests through this HttpHandler is what coordinates the pairing of ScriptService with JavaScriptSerializer to provide automatic JSON handling. </li>
</ul>
<p>Though both of these classes appear in the System.Web.Script namespace, they actually reside in ASP.NET AJAX&#8217;s System.Web.Extensions assembly. That has different implications depending on which version of ASP.NET your site targets:</p>
<ul>
<li><strong>1.x</strong> – No support for ScriptServices. A custom HttpHandler coupled with a third party library like <a href="http://james.newtonking.com/pages/json-net.aspx" target="_blank">Json.NET</a> is your best bet (if anyone has a good tutorial on doing this under 1.x, let me know so that I can link to it).</li>
<li><strong>2.0</strong> – ScriptServices are available in ASP.NET 2.0 with the installation of the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=ca9d90fa-e8c9-42e3-aa19-08e2c027f5d6&amp;displaylang=en" rel="nofollow" target="_blank">ASP.NET AJAX Extensions v1.0</a>.
<ul>
<li>That means that <strong>the ASP.NET AJAX installer needs to be run on the server that hosts your site</strong>, not just on your local development machine.</li>
<li>For some of a ScriptService’s features to work in medium trust (i.e. shared hosting), the System.Web.Extensions assembly needs to be in your server’s global assembly cache (GAC). <a href="http://msmvps.com/blogs/luisabreu/archive/2007/11/22/stop-the-nonsense-don-t-put-the-system-web-extensions-dll-inside-your-bin-folder.aspx" target="_blank">Don’t waste your time trying to make it work in your site’s /bin directory</a>; insist that the extensions be properly installed on the server.</li>
</ul>
</li>
<li><strong>3.5+</strong> – As of .NET 3.5, System.Web.Extensions ships with the framework. No additional assemblies need be installed.</li>
</ul>
<p><em>* If you’re interested in the internals, I highly recommend downloading </em><a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=ef2c1acc-051a-4fe6-ad72-f3bed8623b43&amp;DisplayLang=en" rel="nofollow" target="_blank">the ASP.NET AJAX Extensions v1.0 source</a><em></em><em> and taking a look at ScriptHandlerFactory, RestHandlerFactory, and RestHandler. Though the classes have changed slightly since v1.0, they are still very similar.</em></p>
<h3>Rerouting the ASMX handler via web.config</h3>
<p>With the System.Web.Extensions assembly installed in the GAC, the remaining configuration step is an element in your site’s web.config. To take advantage of the ScriptService functionality, <strong>ASP.NET must be instructed to reroute ASMX requests through the ScriptHandlerFactory instead of ASP.NET’s standard ASMX handler</strong>.</p>
<p>This step is often unnecessary. The project templates in ASP.NET 3.5+ include all the necessary configuration elements, and ASP.NET 2.0 sites created with the “AJAX Enabled” templates are also pre-configured correctly.</p>
<p>However, if you find yourself unable to coax JSON out of an ASMX ScriptService, <strong>verifying your web.config is one of the best first steps in troubleshooting the issue</strong>. Whether due to a web.config generated by an older project template, accidental modification, or other issues, missing the httpHandlers web.config setting is a very common pitfall.</p>
<p>What should appear varies slightly depending on which version of ASP.NET your project targets. Regardless of your framework version, the config elements should be added to the &lt;httpHandlers&gt; section and are the only elements necessary. The <a href="http://www.asp.net/AJAX/documentation/live/ConfiguringASPNETAJAX.aspx" rel="nofollow" target="_blank">variety of other config items required for the UpdatePanel and ScriptManager</a> aren’t crucial to the ScriptService functionality.</p>
<h4>ASP.NET 2.0 (with the ASP.NET AJAX Extensions installed)</h4>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;system.web<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;httphandlers<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;remove</span> <span style="color: #000066;">path</span>=<span style="color: #ff0000;">&quot;*.asmx&quot;</span> <span style="color: #000066;">verb</span>=<span style="color: #ff0000;">&quot;*&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;add</span> <span style="color: #000066;">path</span>=<span style="color: #ff0000;">&quot;*.asmx&quot;</span> <span style="color: #000066;">verb</span>=<span style="color: #ff0000;">&quot;*&quot;</span> <span style="color: #000066;">Culture</span>=neutral, <span style="color: #000066;">validate</span>=<span style="color: #ff0000;">&quot;false&quot;</span></span>
<span style="color: #009900;">           <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;System.Web.Script.Services.ScriptHandlerFactory, </span>
<span style="color: #009900;">                 System.Web.Extensions, Version=1.0.61025.0,</span>
<span style="color: #009900;">                 PublicKeyToken=31bf3856ad364e35&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/httphandlers<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/system.web<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<h4>ASP.NET 3.5</h4>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;system.web<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;httphandlers<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;remove</span> <span style="color: #000066;">path</span>=<span style="color: #ff0000;">&quot;*.asmx&quot;</span> <span style="color: #000066;">verb</span>=<span style="color: #ff0000;">&quot;*&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;add</span> <span style="color: #000066;">path</span>=<span style="color: #ff0000;">&quot;*.asmx&quot;</span> <span style="color: #000066;">verb</span>=<span style="color: #ff0000;">&quot;*&quot;</span> <span style="color: #000066;">Culture</span>=neutral, <span style="color: #000066;">validate</span>=<span style="color: #ff0000;">&quot;false&quot;</span></span>
<span style="color: #009900;">           <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;System.Web.Script.Services.ScriptHandlerFactory, </span>
<span style="color: #009900;">                 System.Web.Extensions, Version=3.5.0.0,</span>
<span style="color: #009900;">                 PublicKeyToken=31bf3856ad364e35&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/httphandlers<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/system.web<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/configuration<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<h4>ASP.NET 4</h4>
<p>Thankfully, <a href="http://www.asp.net/LEARN/whitepapers/aspnet4/default.aspx#_TOC1_1" rel="nofollow" target="_blank">ASP.NET 4 has taken steps to reverse the trend of ever-enlarging baseline web.config files</a>. By moving common configuration items such as the ScriptService’s HttpHandler to the default machine.config, each individual site need not include those configuration elements in their specific web.config files.</p>
<p>Unless you go out of your way to manually remove their HttpHandler, ASMX ScriptServices will work automatically in any ASP.NET 4 site.</p>
<p>Related posts:<ol>
<li><a href='http://encosia.com/asmx-scriptservice-mistake-invalid-json-primitive/' rel='bookmark' title='ASMX ScriptService mistake &#8211; Invalid JSON primitive'>ASMX ScriptService mistake &#8211; Invalid JSON primitive</a></li>
<li><a href='http://encosia.com/asmx-and-json-common-mistakes-and-misconceptions/' rel='bookmark' title='ASMX and JSON &ndash; Common mistakes and misconceptions'>ASMX and JSON &ndash; Common mistakes and misconceptions</a></li>
<li><a href='http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/' rel='bookmark' title='ASP.NET web services mistake: manual JSON serialization'>ASP.NET web services mistake: manual JSON serialization</a></li>
</ol></p><hr />

<p>You've been reading <a href="http://encosia.com/asmx-scriptservice-mistakes-installation-and-configuration/">ASMX ScriptService mistake: Installation and configuration</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p>

<p>If you've got any feedback, please click through and leave a comment; I'd love to hear from you. You can <a href="http://encosia.com/asmx-scriptservice-mistakes-installation-and-configuration/#post-commentblock">click here to jump directly to the comment section of this post</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/asmx-scriptservice-mistakes-installation-and-configuration/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>ASMX and JSON &#8211; Common mistakes and misconceptions</title>
		<link>http://encosia.com/asmx-and-json-common-mistakes-and-misconceptions/</link>
		<comments>http://encosia.com/asmx-and-json-common-mistakes-and-misconceptions/#comments</comments>
		<pubDate>Wed, 03 Mar 2010 09:02:37 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASMX Mistakes and Misconceptions]]></category>
		<category><![CDATA[ASP.NET]]></category>

		<guid isPermaLink="false">http://encosia.com/?p=971</guid>
		<description><![CDATA[While we were recording episode 5 of Mastering jQuery, I found myself running down a lengthy list of misconceptions and potential pitfalls when it comes to using ASMX services for AJAX callbacks. After years of fielding questions revolving around that topic, I suppose I’ve developed a decent handle on the issues most often encountered. To [...]
Related posts:<ol>
<li><a href='http://encosia.com/asmx-scriptservice-mistake-invalid-json-primitive/' rel='bookmark' title='ASMX ScriptService mistake &#8211; Invalid JSON primitive'>ASMX ScriptService mistake &#8211; Invalid JSON primitive</a></li>
<li><a href='http://encosia.com/asmx-scriptservice-mistakes-installation-and-configuration/' rel='bookmark' title='ASMX ScriptService mistake: Installation and configuration'>ASMX ScriptService mistake: Installation and configuration</a></li>
<li><a href='http://encosia.com/are-you-making-these-3-common-aspnet-ajax-mistakes/' rel='bookmark' title='Are you making these 3 common ASP.NET AJAX mistakes?'>Are you making these 3 common ASP.NET AJAX mistakes?</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>While we were recording <a href="http://tekpub.com/view/jquery/5" target="_blank">episode 5 of Mastering jQuery</a>, I found myself running down a lengthy list of misconceptions and potential pitfalls when it comes to using ASMX services for AJAX callbacks. After years of fielding questions revolving around that topic, I suppose I’ve developed a decent handle on the issues most often encountered.</p>
<p>To preemptively surface some of that commonly requested information, I’m going to publish a series of relatively short posts, each describing one mistake or misconception that I’ve seen come up frequently.</p>
<p>To get started, I want to cover one of the most fundamental of these misconceptions:  That ASMX services can&#8217;t return JSON.</p>
<h3>Misconception: ASMX services are limited to XML</h3>
<p>One of the most stubbornly persistent misconceptions about ASMX services is the rumor that they are limited to returning XML. With that notion mind, many developers understandably avoid them for client-side AJAX callbacks. When every byte counts, raw JSON is always preferable to the bloat of XML.</p>
<p>However, the introduction of <strong>ASP.NET AJAX removed that XML limitation</strong>.</p>
<p>In any ASP.NET 2.0+ AJAX enabled site, one of ASP.NET AJAX’s additions is something called the <strong>ScriptService</strong>. When a ScriptService is called in the correct manner, it automatically returns its result serialized as JSON instead of XML.</p>
<p>In fact, these <a href="http://encosia.com/2009/04/07/using-complex-types-to-make-calling-services-less-complex/">ASMX ScriptServices even accept their parameters as JSON</a>.</p>
<h3>The ASP.NET AJAX “ScriptService”</h3>
<p>If you’ve created an ASMX service in the past few years, you’ve probably seen this blurb at the beginning of the default template:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// To allow this Web Service to be called from script, </span>
<span style="color: #008080; font-style: italic;">//   using ASP.NET AJAX, uncomment the following line. </span>
<span style="color: #008080; font-style: italic;">// [System.Web.Script.Services.ScriptService] </span>
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> WebService <span style="color: #008000;">:</span> <span style="color: #000000;">System.<span style="color: #0000FF;">Web</span>.<span style="color: #0000FF;">Services</span></span>.<span style="color: #0000FF;">WebService</span> <span style="color: #000000;">&#123;</span></pre></div></div>

<p>Since it never explicitly mentions JSON <em>and</em> implies a tight coupling with ASP.NET AJAX, it’s easy to understand why the ScriptService’s true power sometimes goes unnoticed. Thankfully, that attribute does much more than simply expose ASP.NET AJAX specific functionality.</p>
<p>In fact, <strong>the ScriptService attribute enables all of an ASMX service’s methods to respond with raw JSON</strong> if they are requested correctly. For example, these ScriptServices can easily <a href="http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/">send and receive JSON in conjunction with a third party library</a>, without a ScriptManager or MicrosoftAjax.js anywhere to be seen.</p>
<h3>Two simple requirements</h3>
<p>As I alluded to earlier, the one stipulation is that <strong>these ScriptServices only return JSON serialized results if they are requested properly</strong>. Otherwise, even a service marked with the attribute will return XML instead of JSON. I can only assume that’s part of the reason for the misconception that ASMX services cannot respond with JSON.</p>
<p>Scott Guthrie has a great post on <a href="http://weblogs.asp.net/scottgu/archive/2007/04/04/json-hijacking-and-how-asp-net-ajax-1-0-mitigates-these-attacks.aspx" target="_blank">the specific requirements for coercing JSON out of ScriptServices</a>. To summarize that, requests to the service methods must meet two requirements:</p>
<ul>
<li><strong>Content-Type</strong> – The HTTP request <em>must</em> declare a content-type of application/json. This informs the ScriptService that it will receive its parameters as JSON and that it should respond in kind.</li>
<li><strong>HTTP Method</strong> – By default, the HTTP request must be a POST request. It <em>is</em> possible to circumvent this requirement, but <a href="http://haacked.com/archive/2009/06/25/json-hijacking.aspx" target="_blank">it is advisable to stick with HTTP POST requests when dealing with JSON</a>.</li>
</ul>
<p>That’s it.</p>
<p>As long as those two requirements are satisfied, anything from low-level XMLHttpRequest code, to third-party libraries like jQuery, to ASP.NET AJAX itself can easily retrieve JSON serialized data from ASMX services.</p>
<p>Related posts:<ol>
<li><a href='http://encosia.com/asmx-scriptservice-mistake-invalid-json-primitive/' rel='bookmark' title='ASMX ScriptService mistake &#8211; Invalid JSON primitive'>ASMX ScriptService mistake &#8211; Invalid JSON primitive</a></li>
<li><a href='http://encosia.com/asmx-scriptservice-mistakes-installation-and-configuration/' rel='bookmark' title='ASMX ScriptService mistake: Installation and configuration'>ASMX ScriptService mistake: Installation and configuration</a></li>
<li><a href='http://encosia.com/are-you-making-these-3-common-aspnet-ajax-mistakes/' rel='bookmark' title='Are you making these 3 common ASP.NET AJAX mistakes?'>Are you making these 3 common ASP.NET AJAX mistakes?</a></li>
</ol></p><hr />

<p>You've been reading <a href="http://encosia.com/asmx-and-json-common-mistakes-and-misconceptions/">ASMX and JSON &ndash; Common mistakes and misconceptions</a>, originally posted at <a href="http://encosia.com">Encosia</a>.  I hope you enjoyed it, and thanks for reading.</p>

<p>If you've got any feedback, please click through and leave a comment; I'd love to hear from you. You can <a href="http://encosia.com/asmx-and-json-common-mistakes-and-misconceptions/#post-commentblock">click here to jump directly to the comment section of this post</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/asmx-and-json-common-mistakes-and-misconceptions/feed/</wfw:commentRss>
		<slash:comments>48</slash:comments>
		</item>
	</channel>
</rss>

