1

As the title says I would like to return json as default instead of XML. In a normal Web API i can edit App_Start/WebApiConfig.cs and add the following line but I can't find where to edit the configuration in Umbraco.

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

I do not wan't my method to return JsonResult to achieve this.

Ogglas
  • 62,132
  • 37
  • 328
  • 418
  • 1
    You can set set `content-type: 'application/json'` and `accept:'application/json` to retrieve the result in json instead of xml – Tinwor Feb 01 '16 at 11:47
  • @Tinwor Yes I know but I would like to get json by default in my API "text/html". – Ogglas Feb 01 '16 at 11:56

3 Answers3

3

I looked at a similar solution first @sebastiaan but decided to override "ApplicationStarting" instead.

public class CustomApplicationEventHandler : ApplicationEventHandler
{
    protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
}

And the WebApiConfig class:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
    }
}
Ogglas
  • 62,132
  • 37
  • 328
  • 418
2

You can create a custom global.asax.cs like so:

using System;
using System.Net.Http.Headers;
using System.Web.Http;
using Umbraco.Web;

namespace MyNamespace
{
    public class CustomGlobal : UmbracoApplication
    {
        private void application_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            var formatters = GlobalConfiguration.Configuration.Formatters;
            formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
        }
    }
}

Update your global.asax as follow then, to point to your CustomGlobal class

<%@ Application Inherits="MyCustomGlobal" Language="C#" %>
sebastiaan
  • 5,870
  • 5
  • 38
  • 68
0

This approach is bad because it returns JSON with a Content-Type of text/html.

See the answer and comments here: https://stackoverflow.com/a/13277616/3537393

A better solution is: https://stackoverflow.com/a/12487921/3537393

LeeC
  • 331
  • 2
  • 12