0

ENV: C# .NET FrameWork 4.6.1

App: ASP.NET MVC

Server Code:

public HttpResponseMessage GetQrCode()
{
    var jsonStr = "{\"IsSuccess\":true,\"Data\":\"somedate\"}";
    var response = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new StringContent(jsonStr, Encoding.UTF8, "text/json")
    };
    return response;
}

Client Code:

HttpClient httpClient = new HttpClient();
var response = await httpClient.PostAsync("http://localhost:18188/home/GetQrCode", null);

var statusCode = response.StatusCode;
string result = await response.Content.ReadAsStringAsync();

result Value:

StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StringContent, Headers:
{
  Content-Type: text/json; charset=utf-8
}

How do I get the values in the response content?
Why did it turn out that way? What's wrong? Thanks

Andrew.Royal
  • 33
  • 1
  • 6
  • The response content-type suggested to be application/json. – talesa82035 Jun 05 '20 at 03:25
  • asp.net serializes your return value to json - you only have to return the value and asp.net will take care for serializing, statuscode, contenttype ... – Sir Rufo Jun 05 '20 at 03:51
  • The answer is that HttpResponseMessage is for WebAPI; you have use ActionResult and Content in ASP.NET MVC. [This answer](https://stackoverflow.com/a/29346121/13801188) explains it and has sample code. – Andy A Aug 02 '20 at 05:10

1 Answers1

0
public ActionResult GetQrCode() => Json(new
{
    IsSuccess = true,
    Data = "somedata"
});

See https://learn.microsoft.com/dotnet/api/system.web.mvc.controller.json

You could also use Content() such that the server determines the serialization by what the user agent accepts (specified in the Accept header), including JSON, XML, as well as custom MIME types if you implement a custom serializer.

TimTIM Wong
  • 788
  • 5
  • 16
  • My requirement is that the return type must be HttpResponseMessage, because the foreground needs to get the response status code, but also need to get the content within the httpResponseMessage, rather than MVC JSONResult – Andrew.Royal Aug 08 '20 at 06:23
  • @Andrew.Royal Your "foreground" is an HTTP client, so the server doesn't even have to be ASP.NET MVC, which defines action handlers that returns an `ActionResult` such as `JsonResult`, and `HttpResponseMessage` does not implement `ActionResult`. – TimTIM Wong Aug 08 '20 at 06:35