ASP .Net MVC6 actions returning strings

2019-08-10 20:15发布

I have the following controller and action.

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

When I call it, I expect action to return "test" (which is valid JSON), but instead it returns test (without quotation marks) is this a valid behavior, or bug? Am I missing something?

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

2条回答
放我归山
2楼-- · 2019-08-10 20:54

It seems that the StringOutputFormatter is getting into your way. If you remove it or move it after the JsonOutputFormatter you will get the desired results.

Output formatters

查看更多
趁早两清
3楼-- · 2019-08-10 21:14

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);
            }
        });
    }

    // ...

}

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

services.AddMvc(options => {
    options.OutputFormatters.RemoveType<StringOutputFormatter>();
});

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.

查看更多
登录 后发表回答