ASP.Net Core控制器操作会为简单字符串生成内容类型的文本/纯文本

Med*_*kal 1 asp.net-mvc asp.net-web-api asp.net-core

我有以下控制器和操作。

[Route("/api/simple")]
public class SimpleController : Controller
{
    [HttpGet]
    [Route("test")]
    public string Test()
    {
        return "test";
    }
}
Run Code Online (Sandbox Code Playgroud)

当我调用它时,我希望有操作返回"test"(这是有效的JSON),但是它会返回test(不带引号),这是有效的行为还是错误?我想念什么吗?

GET http://localhost:5793/api/simple/test HTTP/1.1
User-Agent: Fiddler
Host: localhost:5793
Accept: application/json


HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
Date: Sun, 09 Aug 2015 14:37:45 GMT
Content-Length: 4

test
Run Code Online (Sandbox Code Playgroud)

注意:对于ASP.NET Core 2.0+,当请求中存在Accept标头时,此方法不适用-但是,如果省略了Accept标头并且进行了内容协商,则仍然适用。

leo*_*aro 7

As @mbudnik pointed out, the culprit here is StringOutputFormatter, which somehow gets selected to format the output instead of JsonOutputFormatter. His code snippet, however, no longer works because there’s been some changes to ASP.NET Core since then. Use this instead:

using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Mvc.Formatters;

public class Startup {

    // ...

    public void ConfigureServices(IServiceCollection services) {
        // Add MVC, altering the default output formatters so that JsonOutputFormatter is preferred over StringOutputFormatter
        services.AddMvc(options => {
            var stringFormatter = options.OutputFormatters.OfType<StringOutputFormatter>().FirstOrDefault();
            if (stringFormatter != null) {
                options.OutputFormatters.Remove(stringFormatter);
                options.OutputFormatters.Add(stringFormatter);
            }
        });
    }

    // ...

}
Run Code Online (Sandbox Code Playgroud)

Or, if you think you don't need StringOutputFormatter at all, you can remove it altogether:

services.AddMvc(options => {
    options.OutputFormatters.RemoveType<StringOutputFormatter>();
});
Run Code Online (Sandbox Code Playgroud)

IMO this should be considered a bug, since you asked for a JSON response (Accept: application/json) and returning the string without quotes is definitely not JSON. However, the official position is that this is expected.