Asp.Net Core Mvc JsonResult问题

起因

最近一时兴起,最主要还是有时间,把博客由原来Mono+Nancy改为Asp.Net Core Mvc 3.0,由于.Net Core 3.0还没出正式版,就使用了最新的预览第6版,毕竟出了6个测试版本,API应该趋近于稳定.不料在一个Action返回Json的时候,有些翻车.

使用Json返回json字符串,竟然有异常

在.Net Core Preview 5,使用是没有问题.
public IActionResult UploadFile()
{
    return Json(new { success = true, msg = "" });
}

异常

`1[Microsoft.AspNetCore.Mvc.JsonResult]' has been registered.

突然想起在.Net Core 3.0增加了对json新的API,默认移除Json.Net组件.新的API在System.Text.Json命名空间下.所以便怀疑是不是Asp.Net Core Mvc对新的Json API支持的还不完善.不过这个问题不影响使用.

对比一下Preview 6 和Preview 5 Startup文件中,ConfigureServices函数

perview 6
public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        // This lambda determines whether user consent for non-essential cookies is needed for a given request.
        options.CheckConsentNeeded = context => true;
    });

    services.AddDistributedMemoryCache();
    services.AddSession(options =>
    {
        options.IdleTimeout = TimeSpan.FromHours(1);
        options.Cookie.HttpOnly = true;
        options.Cookie.IsEssential = true;
    });

    services.AddControllersWithViews();  //替代AddMvc
    services.AddRazorPages();
}

preview 5

public void ConfigureServices(IServiceCollection services)
{
    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.AddDistributedMemoryCache();
    services.AddSession(options =>
    {
        options.IdleTimeout = TimeSpan.FromHours(6);
        options.Cookie.HttpOnly = true;
        options.Cookie.IsEssential = true;
    });

    services.AddMvc()     //
            .AddNewtonsoftJson()  //使用Json.Net
            .SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_3_0);
}


方式一

public IActionResult UploadFile()
{
    //使用新的Json API,生成Json字符串
    string json = System.Text.Json.Serialization.JsonSerializer.ToString(new
    {
        success = true,
        msg = "hello Asp.Net Core Mvc"
    });
    return Content(json);
}

方式二

public class People
{
    public string Name { get; set; }

    public string Sex { get; set; }
}


public ActionResult<People> UploadFile()
{
    return new People() { Name = "tom", Sex = "man" };
}
秋风 2019-06-21