【问题标题】:ASP.NET Core HTTPRequestMessage returns strange JSON messageASP.NET Core HTTPRequestMessage 返回奇怪的 JSON 消息
【发布时间】:2016-09-22 14:07:57
【问题描述】:

我目前正在使用 ASP.NET Core RC2,但遇到了一些奇怪的结果。 所以我有一个具有以下功能的 MVC 控制器:

public HttpResponseMessage Tunnel() {
    var message = new HttpResponseMessage(HttpStatusCode.OK);
    message.Content = new StringContent("blablabla", Encoding.UTF8);
    message.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/plain");
    message.Headers.CacheControl = new System.Net.Http.Headers.CacheControlHeaderValue {
        NoCache = true
    };

    return message;
}

如果我用 postman 调用它,并且 Accept 标头设置为纯文本,我会收到以下响应:

{
  "Version": {
    "Major": 1,
    "Minor": 1,
    "Build": -1,
    "Revision": -1,
    "MajorRevision": -1,
    "MinorRevision": -1
  },
  "Content": {
    "Headers": [
      {
        "Key": "Content-Type",
        "Value": [
          "text/plain"
        ]
      }
    ]
  },
  "StatusCode": 200,
  "ReasonPhrase": "OK",
  "Headers": [
    {
      "Key": "Cache-Control",
      "Value": [
        "no-cache"
      ]
    }
  ],
  "RequestMessage": null,
  "IsSuccessStatusCode": true
}

我真的不明白这是如何生成对上述控制器的响应。它基本上是整个消息本身的 JSON 序列化,绝不包含我打算发送的“blablabla”。

获得所需结果的唯一方法是让我的控制器函数返回 string 而不是 HttpResponse,但这样我无法设置像 CacheControl 这样的标题

所以我的问题是:为什么我会得到这个奇怪的响应?这对我来说似乎是非常奇怪的行为

【问题讨论】:

标签: c# asp.net-core asp.net-core-mvc .net-core-rc2


【解决方案1】:

在 ASP.NET Core 中,修改通过管道传输的响应。所以对于标头,直接设置为this answer。 (我已经测试过这个设置 cookie。)你也可以这样设置 HTTP 状态码。

要设置内容并因此使用特定的格式化程序,请遵循文档Format response data in ASP.NET Core Web API。这使您可以使用诸如JsonResult()ContentResult() 之类的帮助程序。

翻译您的代码的完整示例可能是:

[HttpGet("tunnel")]
public ContentResult Tunnel() {
    var response = HttpContext.Response;
    response.StatusCode = (int) HttpStatusCode.OK;
    response.Headers[HeaderNames.CacheControl] = CacheControlHeaderValue.NoCacheString;
    return ContentResult("blablabla", "text/plain", Encoding.UTF8);
}

【讨论】:

    【解决方案2】:

    根据this article,ASP.NET Core MVC 默认不支持HttpResponseMessage-returning 方法。

    如果您想继续使用它,可以使用 WebApiCompatShim:

    1. Microsoft.AspNetCore.Mvc.WebApiCompatShim 的引用添加到您的项目中。
    2. ConfigureServices()中配置:services.AddMvc().AddWebApiConventions();
    3. Configure()为它设置路由:

      app.UseMvc(routes =>
      {
          routes.MapWebApiRoute(
              name: "default",
              template: "{controller=Home}/{action=Index}/{id?}");
      });
      

    【讨论】:

    • @Iarzz11,这个答案应该被接受。对我来说效果很好。
    • 我将"Microsoft.AspNetCore.Mvc.WebApiCompatShim":"1.1.0" 添加到我的project.json,但出现此错误:Package Microsoft.AspNet.WebApi.Client 5.2.2 is not compatible with netcoreapp1.1 (.NETCoreApp,Version=v1.1) 我使用了所有其他version 号码,但仍然出现相同的错误。
    • @HasanAYousef 我认为您需要在 project.json 的 "netcoreapp1.1" 节点下添加类似 "imports": [ "portable-net45+win8" ] 的内容。 (但我还没有测试过。)
    • 如果您只需要能够返回HttpRequestMessage,则不需要设置路由
    • 微软已经详细记录了这一点:docs.microsoft.com/en-us/aspnet/core/migration/…
    【解决方案3】:

    如果你想用字符串内容设置Cache-Control header,试试这个:

    [Produces("text/plain")]
    public string Tunnel()
    {
        Response.Headers.Add("Cache-Control", "no-cache");
        return "blablabla";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-22
      • 1970-01-01
      • 2016-01-31
      • 1970-01-01
      相关资源
      最近更新 更多