Simple Web Service Controller for Office Add-in

I have found Web Service Controllers in Office Add-ins to be quite useful. There are a number of reasons you might want to keep functions of your add-in on a server, including obfuscation, complex calculation, data intense, service mashups, and much more. However, every time you want to use your Web Ser4vice from the JavaScript interface, there is a lot of code associated with the AJAX call you have to make. This begs for simplicity and that is what I have done. In my App.js project, I added a simple makeAjaxCall function that takes the command you want to invoke, the parameters you want to pass it (as an array) a callback when the call is complete and a callback if there was an error. Here is the core code for the makeAjaxCall() method:

// Helper function to call the web service controller
app.makeAjaxCall = function (command, params, callback, error) {
	var dataToPassToService = {
		Command: command,
		Params: params
		url: '../../api/WebService',
		type: 'POST',
		data: JSON.stringify(dataToPassToService),
		contentType: 'application/json;charset=utf-8'
	}).done(function (data) {
	}).fail(function (status) {

Here is a sample of my web service controller:

/// <summary>
/// This function will take a web request which will contain the command the caller wants
/// to initate and then the paramaters needed for that call. We enter a SELECT statement
/// below to determine the command given and we then call the proper helper function
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public WebServiceResponse WebService(WebServiceRequest request)
	WebServiceResponse response = null;
		case "DoFunctionA":
			return functionA(request.Params);
		case "DoFunctionB":
			return functionB(request.Params);
		case "DoFunctionC":
			return functionC(request.Params);
		case "DoFunctionD":
			return functionD(request.Params);

	response = new WebServiceResponse();
	response.Message = "Unknown command";
	return response;

And here is how you call it:

app.makeAjaxCall("DoFunctionA", ["Value1", "Value2"], function (data) {
var result = $.parseJSON(data.Message);
// do something with the retuirned result here...


For more information on how to create a Web Service controller, there is a great blog post from a colleague of mine, Michael Zlatkovsky on how to do this:

Create a web service for an app for Office using the ASP.NET Web API



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s