ASP.NET Core HTTPRequestMessage返回奇怪的JSON消息

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

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

如果我用邮递员调用此方法并将Accept标头设置为text plain,我会收到以下回复:

 { "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这样的头文件

所以我的问题是:为什么我会得到这个奇怪的回答? 这对我来说似乎很奇怪

根据这篇文章 ,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?}"); }); 

如果要使用字符串内容设置Cache-Control标头,请尝试以下操作:

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

在ASP.NET Core中,在响应通过管道时修改响应。 因此,对于标题,请在此答案中直接设置它们。 (我已经测试了这个用于设置cookie。)您也可以这样设置HTTP状态代码。

要设置内容,并因此使用特定的格式化程序,请按照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); }