なか日記

一度きりの人生、楽しく生きよう。

ASP.NET MVCのWeb APIで結果をXMLではなくJSONに変更する

ASP.NET MVCを使ったWebAPIを作成すると、標準ではWebAPIから返される結果がXML形式になると思います。

JSON形式しか使用しない場合には以下の様にXmlFormatterを削除すればJSONで結果が返るようになります。

Global.asax.csに以下の一行を追加します。

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();

            //この一行を追加
            GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
        }
    }