Tutorial: ASP.NET (C#) WCF WebHttp service with jQuery: Part 2 - WCF WebHttp service

See the table of contents for more information.

In the last part we created a Loan object, that we determined we would later use to power our Web service. Ths object has a handful of properties and a method to update a list of payments to bring the loan to $0.

This time we’re going to create a Web service to respond to requests from data.

Requirements

As this seems to be built for .NET Framework 4, you'll want to be running Visual Studio 2010 and .NET Framework 4.

You'll also want to add the WCF REST Service Template 40(CS) to Visual Studio 2010. You can install this by going to Tools > Extension Manager > Online Gallery > Templates > WCF. You can also view more information about this template in the Visual Studio Gallery.

Modifying the WCF template

With the WCF REST Service Template installed you can create a new project and select the template from Online Templates.

You can go ahead and build the template and give it a quick run, just to see how it behaves. With this template, our work is going to be cut significantly in half.

With the project ready, go ahead and either add a reference to the built assembly from part 1, or add the class directly.

Now we'll create a new class for our new service (I've opted to call mine FormulasService.cs) and using the default Service1.cs, add in the necessary references.

using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.ComponentModel;
// depending upon your assembly name, this may be different
using JamesRSkemp.Formulas;

You'll also want to make sure your class has the appropriate attributes.

	[ServiceContract]
	[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
	[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]

Next we'll register the service by opening Global.asax.cs and adding the following, with the string value and typeof dependent upon what you've decided to call your service.

RouteTable.Routes.Add(new ServiceRoute("FormulasService", new WebServiceHostFactory(), typeof(FormulasService)));

Now that our references are added and our route is registered we can try browsing to our service. However, a service must have at least one method, so we'll create a dummy one.

		// todo - remove
		// need at least one method - may as well create a dummy one for validation
		[WebGet(UriTemplate = "Dummy")]
		[Description("Dummy operation.")]
		public String DummyMethod() {
			return "It works.";
		}

Now if we build and start our project we should be able to browse to http://localhost:50996/FormulasService/help and http://localhost:50996/FormulasService/Dummy (swapping out the port accordingly) to see the wonderful documentation that's built into WCF WebHttp services, and our own method.

I've left in some todo items that you can complete later, but now that we've validated things are running okay, we can go ahead and add a new method, such as the following.

[WebGet(UriTemplate = "Loan?name={name}&total={amount}&payment={payment}&yearlyPayments={paymentsPerYear}&yearlyInterest={interestPerYear}")]
[Description("Create a new loan with set properties")]
public Amortization.Loan CreateLoan(String name, String amount, String payment, String paymentsPerYear, String interestPerYear) {
	Double loanAmount, loanPayment, loanInterest;
	int loanPaymentsPerYear;

	Double.TryParse(amount, out loanAmount);
	Double.TryParse(payment, out loanPayment);
	int.TryParse(paymentsPerYear, out loanPaymentsPerYear);
	Double.TryParse(interestPerYear, out loanInterest);

	// todo - validation of items > 0

	// todo - validation that the loan terms make sense (interest < payments)

	// If everything looks okay, create a new loan.
	Amortization.Loan newLoan = new Amortization.Loan();
	newLoan.Name = name;
	newLoan.Total = loanAmount;
	newLoan.PaymentAmount = loanPayment;
	newLoan.PaymentsPerYear = loanPaymentsPerYear;
	newLoan.InterestPerYear = loanInterest;

	try {
		newLoan.UpdatePayments();
	} catch (Exception ex) {
		newLoan.Name = ex.Message + " | " + ex.StackTrace;
		// todo, throw appropriate error here
	}

	return newLoan;
}

As you can see, I'm allowing GET requests, and am having them pass everything we need to generate a loan, with payments. Note that the method uses strings instead of the appropriate type. Feel free to modify this, but the service will throw an error.

Build and start the project and you should be able to browse to http://localhost:50996/FormulasService/Loan?name=asdf&total=4956.24&payment=97.85&yearlyPayments=12&yearlyInterest=4.25 (changing the port as needed) to view returned data, in XML format.

If we'd prefer, we can change this to return JSON instead, either by adding an attribute or modifying the standardEndpoint element in Web.config, by adding something like defaultOutgoingResponseFormat="Json".

For more information on how this works, read Automatic and Explicit Format Selection in WCF WebHttp Services.

Next time …

Now that we have a working WCF WebHttp service, that responds to GET requests with XML data, we can look at how we can interact with this service with jQuery, and have the service return JSON results.