MVC REST services in Umbraco 4

Create a Global.asax file for your Umbraco project. In the Application_Start method register the MVC routes:

protected void Application_Start()
  RouteTable.Routes.MapRoute("ServiceRoute", "Services/{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    new string[] { "Your.Namespace.For.Mvc.Controllers" });

Because Umbraco already contains an empty compiled Global.asax/HttpApplication class in the bin folder, you must delete the “bin/App_global.asax.dll” file. You might read other ways to register Application_Start events in Umbraco. However I never managed to get this to work.

You also need to instruct Umbraco to ignore URLs for the MVC controllers. In Umbraco’s web.config’s change the “umbracoReservedPaths” app setting:

  <add key="umbracoReservedPaths" value="~/umbraco,~/install/,~/Services/" />

Setting Content-Type in an Umbraco /Base service

The Umbraco /Base system is great for creating simple REST-like services. You can use the RestExtensionMethod attribute to instruct Umbraco to return your response as XML or not. But what is “not”? Apparently it means set Response.ContentType to “text/html”. But what if the returned data should be sent using a different mime type? Setting the ContentType manually like

HttpContext.Current.Response.ContentType = "application/json"

will not do the trick. Umbraco /Base will override it with “text/html” if you are returning a string from your service method.

What you need to do is to change your method return signature to “void” and write your data directly to the HttpResponse, like:

HttpContext.Current.Response.ContentType = "application/json";

Umbraco will not override the content type for “void”-methods. Below is a full example.

public class MemberService
	[RestExtensionMethod(returnXml = false, allowAll = true)]
	public static void Json()
		var json = "{ \"firstName\": \"John\", \"lastName\": \"Smith\", \"age\": 25 }";

		// Write response and set content type
		HttpContext.Current.Response.ContentType = "application/json";