Custom media type formatter for Json Api (1.0) responses and requests.
Inheritance: System.Net.Http.Formatting.MediaTypeFormatter
示例#1
0
        /// <summary>
        ///  Sets up serialization and deserialization of Json Api resources.
        /// </summary>
        /// <param name="config">The <see cref="HttpConfiguration"/> that is used in the setup of the application.</param>
        /// <param name="jsonApiConfiguration">JsonApiConfiguration parameters for Json Api serialization.</param>
        /// <param name="formatterPriority"> Determines the relative position of the JSON API formatter.</param>
        public static void ConfigureJsonApi(
            this HttpConfiguration config,
            JsonApiConfiguration jsonApiConfiguration,
            FormatterPriority formatterPriority)
        {
            JsonApiAttribute.JsonApiConfiguration = jsonApiConfiguration;

            config.MessageHandlers.Add(new PreprocessingDelegatingHandler(jsonApiConfiguration));

            config.Services.Add(typeof(ValueProviderFactory), new JsonApiQueryValueProviderFactory());

            var formatter = new JsonApiMediaTypeFormatter(jsonApiConfiguration);

            if (formatterPriority == FormatterPriority.OverwriteOtherFormatters)
            {
                config.Formatters.Clear();
                config.Formatters.Add(formatter);
            }
            else if (formatterPriority == FormatterPriority.AddFormatterToEnd)
            {
                config.Formatters.Add(formatter);
            }
            else if (formatterPriority == FormatterPriority.AddFormatterToStart)
            {
                config.Formatters.Insert(0, formatter);
            }
        }
        internal ObsoleteSetupJsonApiServer(JsonApiMediaTypeFormatter formatter)
        {
            var config = new HttpConfiguration();
            config.Formatters.Clear();
            config.Formatters.Add(formatter);
            config.MapHttpAttributeRoutes(new DefaultDirectRouteProvider());

            _server = TestServer.Create(builder =>
            {
                builder.UseWebApi(config);
            });
        }
            public async Task ConverterConstructorObsolete()
            {
                var formatter = new JsonApiMediaTypeFormatter(
                    new StringEnumConverter());

                using (var server = new ObsoleteSetupJsonApiServer(formatter))
                {
                    var client = server.GetClient();
                    var result = await client.GetJsonResponseAsync("api/companies/456/");
                    _output.WriteLine(result.ToString());

                    Assert.Equal("National", result["data"]["attributes"]["location"].Value<string>());
                }
            }
            public async Task UrlBuilderConstructorObsolete()
            {
                var formatter = new JsonApiMediaTypeFormatter(
                    new CanonicalUrlPathBuilder());

                using (var server = new ObsoleteSetupJsonApiServer(formatter))
                {
                    var client = server.GetClient();
                    var result = await client.GetJsonResponseAsync("api/people/");
                    _output.WriteLine(result.ToString());

                    var relatedUrl = result["data"][0]["relationships"]["job"]["links"]["related"]
                        .Value<string>();
                    Assert.Equal("http://localhost/corporations/456/", relatedUrl);
                }
            }
示例#5
0
        /// <summary>
        /// Sets up serialization and deserialization of Json Api resources.
        /// </summary>
        /// <param name="config">The <see cref="HttpConfiguration"/> that is used in the setup of the application.</param>
        /// <param name="jsonApiConfiguration">Configuration parameters for Json Api serialization.</param>
        /// <param name="overwriteOtherFormatters">
        /// If true, other formatters will be cleared. Otherwise, the JSON API formatter
        /// will be inserted at the start of the collection.
        /// </param>
        public static void ConfigureJsonApi(
            this HttpConfiguration config,
            JsonApiConfiguration jsonApiConfiguration,
            bool overwriteOtherFormatters)
        {
            config.MessageHandlers.Add(new PreprocessingDelegatingHandler(jsonApiConfiguration));
            var formatter = new JsonApiMediaTypeFormatter(jsonApiConfiguration);

            if (overwriteOtherFormatters)
            {
                config.Formatters.Clear();
                config.Formatters.Add(formatter);
            }
            else
            {
                config.Formatters.Insert(0, formatter);
            }
        }
        /// <summary>
        /// Sets up serialization and deserialization of Json Api resources.
        /// </summary>
        /// <param name="config">The <see cref="HttpConfiguration"/> that is used in the setup of the application.</param>
        /// <param name="jsonApiConfiguration">Configuration parameters for Json Api serialization.</param>
        /// <param name="overwriteOtherFormatters">
        /// If true, other formatters will be cleared. Otherwise, the JSON API formatter
        /// will be inserted at the start of the collection.
        /// </param>
        public static void ConfigureJsonApi(
            this HttpConfiguration config,
            JsonApiConfiguration jsonApiConfiguration,
            bool overwriteOtherFormatters)
        {
            config.MessageHandlers.Add(new PreprocessingDelegatingHandler(jsonApiConfiguration));
            var formatter = new JsonApiMediaTypeFormatter(jsonApiConfiguration);

            if (overwriteOtherFormatters)
            {
                config.Formatters.Clear();
                config.Formatters.Add(formatter);
            }
            else
            {
                config.Formatters.Insert(0, formatter);
            }
        }
            public async Task DefaultConstructorObsolete()
            {
                var formatter = new JsonApiMediaTypeFormatter();

                using (var server = new ObsoleteSetupJsonApiServer(formatter))
                {
                    var client = server.GetClient();
                    var result = await client.GetJsonResponseAsync("api/companies/456/");
                    _output.WriteLine(result.ToString());

                    Assert.Equal(1, result["data"]["attributes"]["location"].Value<int>());

                    result = await client.GetJsonResponseAsync("api/people/");
                    _output.WriteLine(result.ToString());

                    var relatedUrl = result["data"][0]["relationships"]["job"]["links"]["related"]
                        .Value<string>();
                    Assert.Equal("http://localhost/api/people/0/employer/", relatedUrl);
                }
            }
        /// <summary>
        /// See base class documentation.
        /// </summary>
        /// <param name="context">The action context.</param>
        public override void OnActionExecuted(HttpActionExecutedContext context)
        {
            if (context.Exception != null)
            {
                throw context.Exception;
            }

            JsonApiProcessor.ProcessRequest(context.Request, context.Response, JsonApiConfiguration, requiresMediaType: false);

            var responseContent = context.Response.Content as ObjectContent;

            if (responseContent == null)
            {
                return;
            }

            var formatter = new JsonApiMediaTypeFormatter(context.Request, JsonApiConfiguration);

            context.Response.Content = new ObjectContent(responseContent.ObjectType, responseContent.Value, formatter);
        }
示例#9
0
        /// <summary>
        ///  Sets up serialization and deserialization of Json Api resources.
        /// </summary>
        /// <param name="config">The <see cref="HttpConfiguration"/> that is used in the setup of the application.</param>
        /// <param name="jsonApiConfiguration">Configuration parameters for Json Api serialization.</param>
        /// <param name="formatterPriority"> Determines the relative position of the JSON API formatter.</param>
        public static void ConfigureJsonApi(
            this HttpConfiguration config,
            JsonApiConfiguration jsonApiConfiguration,
            FormatterPriority formatterPriority)
        {
            config.MessageHandlers.Add(new PreprocessingDelegatingHandler(jsonApiConfiguration));
            var formatter = new JsonApiMediaTypeFormatter(jsonApiConfiguration);

            if (formatterPriority == FormatterPriority.OverwriteOtherFormatters)
            {
                config.Formatters.Clear();
                config.Formatters.Add(formatter);
            }
            else if (formatterPriority == FormatterPriority.AddFormatterToEnd)
            {
                config.Formatters.Add(formatter);
            }
            else if (formatterPriority == FormatterPriority.AddFormatterToStart)
            {
                config.Formatters.Insert(0, formatter);
            }
        }
            public async Task GivesUsefulErrorObsolete()
            {
                var formatter = new JsonApiMediaTypeFormatter();

                using (var server = new ObsoleteSetupJsonApiServer(formatter))
                {
                    var client = server.GetClient();
                    var result = await client.GetJsonResponseAsync("api/broken/123/");
                    _output.WriteLine(result.ToString());

                    var error = result["errors"][0];

                    Assert.Equal("https://github.com/joukevandermaas/saule/wiki",
                        error["links"]["about"].Value<string>());

                    Assert.Equal("Saule.JsonApiException",
                        error["code"].Value<string>());

                    Assert.Equal("Saule.JsonApiException: You must add a [ReturnsResourceAttribute] to action methods.",
                        error["detail"].Value<string>());
                }
            }
            public async Task AppliesSortingBeforePaginationObsolete(string path)
            {
                var formatter = new JsonApiMediaTypeFormatter();

                using (var server = new ObsoleteSetupJsonApiServer(formatter))
                {
                    var client = server.GetClient();
                    var result1 = await client.GetJsonResponseAsync($"api/{path}/people?sort=age");
                    var result2 = await client.GetJsonResponseAsync($"api/{path}/people?sort=age&page[number]=1");
                    _output.WriteLine(result1.ToString());
                    _output.WriteLine(result2.ToString());

                    var ages1 = ((JArray)result1["data"])
                        .Select(p => p["attributes"]["age"].Value<int>())
                        .ToList();
                    var ages2 = ((JArray)result2["data"])
                        .Select(p => p["attributes"]["age"].Value<int>())
                        .ToList();

                    var sorted = ages1.Concat(ages2).OrderBy(a => a).ToList();

                    Assert.Equal(sorted, ages1.Concat(ages2).ToList());
                }
            }
            public async Task AppliesSortingConditionallyObsolete()
            {
                var formatter = new JsonApiMediaTypeFormatter();

                using (var server = new ObsoleteSetupJsonApiServer(formatter))
                {
                    var client = server.GetClient();
                    var result = await client.GetJsonResponseAsync("api/people?sort=age");
                    _output.WriteLine(result.ToString());

                    var ages = ((JArray)result["data"])
                        .Select(p => p["attributes"]["age"].Value<int>())
                        .ToList();
                    var sorted = ages.OrderBy(a => a).ToList();

                    Assert.NotEqual(sorted, ages);
                }
            }
            public async Task AppliesFilteringObsolete()
            {
                var formatter = new JsonApiMediaTypeFormatter();

                using (var server = new ObsoleteSetupJsonApiServer(formatter))
                {
                    var client = server.GetClient();
                    var result = await client.GetJsonResponseAsync("api/query/people?filter[last-name]=Russel");
                    _output.WriteLine(result.ToString());

                    var names = ((JArray)result["data"])
                        .Select(p => p["attributes"]["last-name"].Value<string>())
                        .ToList();

                    var filtered = names.Where(a => a == "Russel").ToList();

                    Assert.Equal(filtered.Count, names.Count);
                }
            }
            public async Task AppliesPaginationObsolete()
            {
                var formatter = new JsonApiMediaTypeFormatter();

                using (var server = new ObsoleteSetupJsonApiServer(formatter))
                {
                    var client = server.GetClient();
                    var result = await client.GetJsonResponseAsync("api/companies/");
                    _output.WriteLine(result.ToString());

                    Assert.Equal(12, (result["data"] as JArray)?.Count);
                }
            }
 public void TestMethod1()
 {
     var formatter = new JsonApiMediaTypeFormatter();
     Assert.Equal(1, formatter.SupportedMediaTypes.Count);
     Assert.Equal(Constants.MediaType, formatter.SupportedMediaTypes.First().MediaType);
 }