WCF return JSON, AJAX-enabled WCF Service in less than 3 minutes

I was about to set up some WCF services to handle POST requests to SolrNet and was digging around for solution. Goal was to post a string query to the web service and get JSON objects returned. This can be obtained pretty easily with an AJAX-enabled WCF Service and a bit of jQuery.

Actually you can have this example going in less than 3 minutes!

To serialize my objects to JSON I’m using a ToJson extension method written by Scott Gu. This makes it very easy to just use .ToJson() on your objects or collections, just like using ToString().

Steps to build the web service

1. Create a new WCF Service Application and delete the files IService1.cs and Service1.svc
2. Right click your solution and Add New Item. Search for “Ajax enabled” and choose AJAX-enabled WCF Service.
3. Create a folder called “Helpers” in which you create a static class called “JsonHelper” with the following methods:
[csharp]
public static class JsonHelper
{
public static string ToJson(this object obj)
{
var serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}

public static string ToJson(this object obj, int recursionDepth)
{
var serializer = new JavaScriptSerializer();
serializer.RecursionLimit = recursionDepth;
return serializer.Serialize(obj);
}
}
[/csharp]

The method takes your object, serializes it to JSON and returns it.

4. Open up your newly created AJAX-enabled WCF Service – Service1.svc and delete the method OperationContract method DoWork().
5. Create a new OperationContract method called HelloWorld() which will look like this:
[csharp]
[OperationContract]
public string HelloWorld(string personName)
{
return (new HelloWorldWrapper
{
Response = string.Format("Hello, {0}", personName),
Error = "",
TimeExecuted = DateTime.Now.ToString(CultureInfo.InvariantCulture)
}).ToJson();
}
[/csharp]

6. Create a wrapper class for your Hello World method, which we will create a new object of, serialize to JSON and return.
[csharp]
public class HelloWorldWrapper
{
public string Response;
public string TimeExecuted;
public string Error;
}
[/csharp]

Test test test!

Now you are actually done, but lets test the service. For that we’ll need a HTML page where we execute some jQuery and call our web service. Note that this service will be hosted on a IIS, where as your your front-end call can be on what ever server and site you want.

Right click your project and Add New Item. Create a Web Form for the ease of it.
In the head section insert:
[js]
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
var personNameVar = "Paul";
var dataIn = ‘{‘ + ‘"personName":"’ + personNameVar + ‘"}’;
$.ajax({
url: "/Service1.svc/HelloWorld",
type: "POST",
contentType: "application/json; charset=utf-8",
data: dataIn,
dataType: "json",
success: function (data) {
var object = JSON.parse(data.d);
if (object.Error == ”) {
//Alert the persons name
alert(object.Response);
}
},
error: function (error) {
alert("Error: " + error.Error);
}
});
</script>
[/js]

We are making an AJAX-call to our web service, located at “/Service1.svc/HelloWorld”, sending a post request in JSON format, containing the string personName. In our success function we receive our JSON serialized object and get the Reponse string returned in a alert box.

CTRL+SHIFT+B your project, right click HelloWorld.aspx and “View in Browser”.

For the lazy ones i made a Visual Studio 2012 project on .NET 4.5 framework containing the example. Download: Ajax WCF Test

Run URL from ASP.NET/C#

Sometimes it can be handy to run a URL from a ASP.NET page (eg. aspx, ascx or MVC control). It could be simply executing one or more webservices, without wanting a result back.

It’s actually pretty simple!

[csharp]
string url = "http://egeek.dk/service.ashx";
using (System.Net.WebClient client = new System.Net.WebClient())
{
client.DownloadString(url);
}
[/csharp]

An error occurred during the parsing of a resource required to service this request

I suddenly got this error in my ASP.NET Web Forms project in Visual Studio. Even after creating a new Web Form without content, I was thrown this error. The solution was very simple. All you have to do is rebuild your project.

Server Error in ‘/’ Application.


Parser Error

Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

Parser Error Message: Could not load type ‘Listing’.

Source Error:

Line 1: <%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”8-8_Listing.aspx.cs” Inherits=”Listing” %> Line 2:
Line 3: <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>


Source File: /8-8_Listing.aspx Line: 1