asp.net core 3.0不能返回JsonResult?

2019-06-24 18:29发布

问题:

新建一个asp.net core 3.0的项目不能返回JsonResult。.NET Core SDK版本 3.0.100-preview6-012264 

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
}


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}
public IActionResult Index()
{
    return Json(new { name = "tom" });
}

 

回答1:

Nuget 安装 Microsoft.AspNetCore.Mvc.NewtonsoftJson

<ItemGroup>
  <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0-preview6.19307.2" />
</ItemGroup>

Startup 中添加 AddNewtonsoftJson()

services.AddControllersWithViews().AddNewtonsoftJson();