【发布时间】:2019-05-26 23:04:47
【问题描述】:
我可以使用以下方式从普通 WebApi 中检索预期的 json 结果。
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddJsonOptions(x=>
{
x.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
});
但是当使用 ODataController 而不是使用 Web api 时的 ControllerBase 时,我找不到像这样输出 json 的方法。 ODataController 总是发送一个缩小的 json。
public class EmployeeController : ODataController
{
[EnableQuery()]
public IActionResult Get()
{
return Ok(new BOContext().Employees.ToList());
}
}
还有,startup.cs
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?}");
});
}
}
路线正在运行,我正在接收正确的数据。
有没有办法从 OData 控制器控制和输出缩进的 json?
【问题讨论】:
-
您是否有任何具体原因希望返回缩进 json 而不是资源友好的最小化版本?
-
我正在构建一种后端,其中视图显示一些要编辑的 json。这是一些高级用户使用的。为了可用性,它应该是一个可读的 json。如果这可以由服务器处理,那就太好了。
标签: asp.net-core odata entity-framework-core asp.net-core-webapi asp.net-core-2.1