Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

c# - ASP.NET Core HTTPRequestMessage returns strange JSON message

I am currently working with ASP.NET Core RC2 and I am running into some strange results. So I have an MVC controller with the following 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;
}

If I call this with postman with an Accept header set to text plain I get this response:

{
  "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
}

I really do not understand how this is the generated reponse to the above controller. It is basically a JSON serialization of the entire message itself and does in no way contain the "blablabla" I intended to send.

The only way I have gotten the desired result is by making my controller function return string instead of HttpResponse, but that way I am unable to set headers like CacheControl

So my question is: why do I get this strange response? It seems like very weird behaviour to me

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

According to this article, ASP.NET Core MVC does not support HttpResponseMessage-returning methods by default.

If you want to keep using it, you can, by using WebApiCompatShim:

  1. Add reference to Microsoft.AspNetCore.Mvc.WebApiCompatShim to your project.
  2. Configure it in ConfigureServices(): services.AddMvc().AddWebApiConventions();
  3. Set up route for it in Configure():

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...