【问题标题】:ASP.Net Core controller actions produces content type text/plain for simple stringsASP.Net Core 控制器操作为简单字符串生成内容类型 text/plain
【发布时间】:2015-08-09 14:41:10
【问题描述】:

我有以下控制器和动作。

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

当我调用它时,我希望操作返回 "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

注意:对于 ASP.NET Core 2.0+,这在请求中存在 Accept 标头时不适用 - 但如果 Accept 标头被省略并且发生内容协商,它仍然适用。

【问题讨论】:

  • 如果您确实希望它返回引号使用转义序列,这是有效的行为:return "\"Test\"";
  • @BryanMudge 但是,我期待一个 json 输出。 'test' 不是一个有效的 JSON,例如,如果我返回一个对象,它会序列化该对象。
  • 问题存在对象的双重序列化。但在这种情况下,它根本不序列化。

标签: asp.net-mvc asp.net-web-api asp.net-core


【解决方案1】:

正如@mbudnik 所指出的,这里的罪魁祸首是StringOutputFormatter,它以某种方式被选中来格式化输出而不是JsonOutputFormatter。然而,他的代码 sn-p 不再有效,因为从那时起 ASP.NET Core 发生了一些变化。改用这个:

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

    // ...

}

或者,如果你认为你根本不需要 StringOutputFormatter,你可以完全删除它:

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

IMO 这应该被视为一个错误,因为您要求 JSON 响应 (Accept: application/json) 并且返回不带引号的字符串绝对是 不是 JSON。但是,the official position is that this is expected

【讨论】:

    【解决方案2】:

    似乎 StringOutputFormatter 正在妨碍您。 如果将其删除或移动到 JsonOutputFormatter 之后,您将获得所需的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-11
      • 2013-02-28
      • 1970-01-01
      • 2015-06-08
      • 2012-03-28
      • 1970-01-01
      相关资源
      最近更新 更多