예제 #1
0
 public static void SelectFields_Should_Throws_Exception_When_Param_Is_Null()
 {
     // act & assert
     Assert.Throws <ArgumentNullException>(() => JsonFieldSelectorExtension.SelectFieldsFromObject <object>(null, new string[] { })); // by obj
     Assert.Throws <ArgumentNullException>(() => JsonFieldSelectorExtension.SelectFieldsFromJToken(null, new string[] { }));          // by jtoken
     Assert.Throws <ArgumentNullException>(() => JsonFieldSelectorExtension.SelectFieldsFromString(null, new string[] { }));          // by string
 }
        public async Task Invoke(HttpContext context)
        {
            await this.Next(context);

            if (context.Request.Query.Any(r => r.Key.ToLowerInvariant() == this.PropertyName))
            {
                var json = context.Response.Body.AsString();

                if (string.IsNullOrWhiteSpace(json))
                {
                    return;
                }

                try
                {
                    var fields = context.Request.Query
                                 .FirstOrDefault(r => r.Key.ToLowerInvariant() == this.PropertyName)
                                 .Value.ToString();

                    if (string.IsNullOrWhiteSpace(fields))
                    {
                        json = "{ }";
                    }
                    else
                    {
                        json = JsonFieldSelectorExtension.SelectFieldsFromString(json, fields);
                    }
                }
                catch
                {
                    json = "{ }";
                }

                var length = Encoding.UTF8.GetBytes(json ?? "").Length;
                context.Response.Body.SetLength(length);
                context.Response.ContentLength = length;
                await context.Response.WriteAsync(json);
            }
        }