Подтвердить что ты не робот

Как изменить стандартный Web API 2 для форматирования JSON?

У меня есть проект веб-API, который возвращает некоторые данные о продуктах. Он корректно согласовывает тип возврата в зависимости от заголовка Accept (JSON/XML) запроса. Проблема в том, что если заголовок Accept не указан, он возвращает XML, но я хочу, чтобы он возвращал JSON по умолчанию.

http://website.com/MyPage?type=json // returns json
http://website.com/MyPage?type=xml // returns xml
http://website.com/MyPage // returns xml by default

Вот мой текущий код выглядит следующим образом:

GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(
new QueryStringMapping("type", "xml", new MediaTypeHeaderValue("application/xml")));

GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(
new QueryStringMapping("type", "json", new MediaTypeHeaderValue("application/json")));
4b9b3361

Ответ 1

Добавьте это в свой App_Start/WebApiConfig.cs:

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

Ответ 2

Я думаю, что Web API просто использует первый форматтер, который он может найти в коллекции Formatters. Вы можете изменить порядок с помощью чего-то вроде

GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());
GlobalConfiguration.Configuration.Formatters.Add(new XmlMediaTypeFormatter());

Но похоже, что форматирование JSON должно быть первым по умолчанию, поэтому вы можете проверить, не изменили ли вы эту коллекцию где-нибудь.

Ответ 3

Я думаю, вы должны измениться следующим образом. Global.asax:

/*For Indented formatting:*/       
 GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;

    /*Response as default json format
     * example (http://localhost:9090/WebApp/api/user/)
     */
    GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

    /*Response as json format depend on request type
     * http://localhost:9090/WebApp/api/user/?type=json
     */
    GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(
    new QueryStringMapping("type", "json", new MediaTypeHeaderValue("application/json")));

    /*Response as xml format depend on request type
     * http://localhost:9090/WebApp/api/user/?type=xml
     */
    GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(
    new QueryStringMapping("type", "xml", new MediaTypeHeaderValue("application/xml")));

Ответ 4

Или просто удалите XmlFormatter

var formatters = GlobalConfiguration.Configuration.Formatters;
formatters.Remove(formatters.XmlFormatter);

Ответ 5

Ни один из вышеперечисленных ответов не работал у меня. Проблема заключалась в том, что я получал форматы от GlobalConfiguration, а не от объекта config, созданного с помощью new HttpConfiguration(). Вот код, который работает для меня:

public class WebApiConfig
{
    public static HttpConfiguration Register()
    {

        var config = new HttpConfiguration();
        // This next line could stay if you want xml formatting
        config.Formatters.Remove(config.Formatters.XmlFormatter);

        // This next commented out line was causing the problem
        //var jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;

        // This next line was the solution
        var jsonFormatter = config.Formatters.JsonFormatter;
        jsonFormatter.UseDataContractJsonSerializer = false; // defaults to false, but no harm done
        jsonFormatter.SerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
        jsonFormatter.SerializerSettings.Formatting = Formatting.None;
        jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();           

        // remaining irrelevant code commented out
        return config;
    }
}

Ответ 6

config.EnableSystemDiagnosticsTracing();

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

// Adding formatter for Json   
config.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("type", "json", new MediaTypeHeaderValue("application/json")));

// Adding formatter for XML   
config.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("type", "xml", new MediaTypeHeaderValue("application/xml")));