如何从ASP核心Web API中的OData控制器返回缩进的JSON内容?

时间:2018-12-29 13:41:48

标签: asp.net-core odata entity-framework-core asp.net-core-webapi asp.net-core-2.1

我可以使用以下方法从普通WebApi中检索预期的json结果。

public class EmployeeController : ODataController
{

    [EnableQuery()]
    public IActionResult Get()
    {
        return Ok(new BOContext().Employees.ToList());
    }
}

但是当使用OAPI而不是使用Web api的ControllerBase时,我找不到一种输出json的方法。 ODataController总是发送一个缩小的json。

 public class Startup
    {
        private static IEdmModel GetModel()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            builder.EntitySet<Employee>("Employee");
            return builder.GetEdmModel();
        }

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddOData();
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });



            services.AddMvc()
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
                .AddJsonOptions(x=>
                {
                    x.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.None;
                });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapODataServiceRoute("odata", "odata", GetModel());
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

            });
        }
    }

另外,startup.cs

textarea {
     color: #444;
     padding: 5px;
}
.txtstuff {
    resize: none;
    overflow: hidden;
}
.hiddendiv {
    display: none;
    white-space: pre-wrap;
    word-wrap: break-word;
    overflow-wrap: break-word
}
.common {
    width: 500px;
    min-height: 50px;
    font-family: Arial, sans-serif;
    font-size: 13px;
    overflow: hidden;
}
.lbr {
    line-height: 3px;
}

该路由正在运行,我正在接收正确的数据。

是否可以通过OData控制器控制和输出缩进的json?

2 个答案:

答案 0 :(得分:1)

我建议您使用缩小的jsonm进行传输,但请使用json beutifier显示格式化的json。不要在数据流阶段这样做。

如果您在前端使用javascript。您可以简单地使用

JSON.stringify(jsObj, null, "\t"); // stringify with tabs inserted at each level
JSON.stringify(jsObj, null, 2);    // stringify with 2 spaces at each level

答案 1 :(得分:0)

不确定这是否仍然可行,但是您可以在返回数据时指定格式化程序

// [...]
public IActionResult Get()
        {
            var res = Ok(_db.Employees);
            res.Formatters.Add(new Microsoft.AspNetCore.Mvc.Formatters.JsonOutputFormatter(
                new Newtonsoft.Json.JsonSerializerSettings() { Formatting = Newtonsoft.Json.Formatting.Indented }, 
                System.Buffers.ArrayPool<char>.Create()));
            return res;
        }

当然,如果您需要更通用的解决方案(或者您已经编写了很多代码),则可以创建临时抽象类并从该类继承,而不仅仅是ODataController

public abstract class AbstractFormattedOdataController : ODataController
    {
        public override OkObjectResult Ok(object value)
        {
            var res = base.Ok(value);
            res.Formatters.Add(new Microsoft.AspNetCore.Mvc.Formatters.JsonOutputFormatter(
                new Newtonsoft.Json.JsonSerializerSettings() { Formatting = Newtonsoft.Json.Formatting.Indented },
                System.Buffers.ArrayPool<char>.Create()));
            return res;
        }
    }
// [...]
public class EmployeesController : AbstractFormattedOdataController 
{
    [EnableQuery()]
    public IActionResult Get()
    {
        return Ok(new BOContext().Employees.ToList());
    }
}