How do I set a value for HttpResponseMessage.Content in C#

huangapple go评论60阅读模式
英文:

How do I set a value for HttpResponseMessage.Content in C#

问题

I have a Web API method that returns data in the HttpResponseMessage.Content property. Here is the code for the method:

[HttpGet]
public HttpResponseMessage MethodName()
{
try
{
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StringContent("Hello WORLD", Encoding.UTF8, "application/json");
return response;
}
catch (Exception ex)
{
var response = new HttpResponseMessage(HttpStatusCode.InternalServerError);
response.Content = new StringContent("{"error": "" + ex.Message + ""}", Encoding.UTF8, "application/json");
return response;
}
}

When I call this method from Postman, the response metadata shows that the response has a length of 11, which is correct for the "Hello WORLD" string. However, I cannot see the actual data in the response body.

What am I missing?

Here is the response:

{
"version": "1.1",
"content": {
"headers": [
{
"key": "Content-Type",
"value": [
"application/json; charset=utf-8"
]
},
{
"key": "Content-Length",
"value": [
"11"
]
}
}
},
"statusCode": 200,
"reasonPhrase": "OK",
"headers": [],
"trailingHeaders": [],
"requestMessage": null,
"isSuccessStatusCode": true
}

英文:

I have a Web API method that returns data in the HttpResponseMessage.Content property. Here is the code for the method:

[HttpGet]
public HttpResponseMessage MethodName()
{
    try
    {
        var response = new HttpResponseMessage(HttpStatusCode.OK);
        response.Content = new StringContent("Hello WORLD", Encoding.UTF8, "application/json");
        return response;
    }
    catch (Exception ex)
    {
        var response = new HttpResponseMessage(HttpStatusCode.InternalServerError);
        response.Content = new StringContent("{\"error\": \"" + ex.Message + "\"}", Encoding.UTF8, "application/json");
        return response;
    }
}

When I call this method from Postman, the response metadata shows that the response has a length of 11, which is correct for the "Hello WORLD" string. However, I cannot see the actual data in the response body.

What am I missing?

Here is the response:
<!-- language: json -->
{
"version": "1.1",
"content": {
"headers": [
{
"key": "Content-Type",
"value": [
"application/json; charset=utf-8"
]
},
{
"key": "Content-Length",
"value": [
"11"
]
}
]
},
"statusCode": 200,
"reasonPhrase": "OK",
"headers": [],
"trailingHeaders": [],
"requestMessage": null,
"isSuccessStatusCode": true
}

答案1

得分: 1

以下是您要翻译的内容:

如果您将 IActionResult 用作方法的返回类型,那么您可以利用基类的 OkStatusCode 方法。您的方法可以重写如下:

[HttpGet]
public IActionResult MethodName()
{
    try
    {
        return Ok("Hello WORLD");
    }
    catch (Exception ex)
    {
        return StatusCode((int)HttpStatusCode.InternalServerError, "{\"error\": \"" + ex.Message + "\"}");
    }
}

坦率地说,我不真正理解您的 try-catch 块的唯一目的,但我希望您明白我的意思。

更新 #1
> 为什么我不能正确设置 HttpResponseMessage.Content

StringContent 只有一个名为 Headers 的属性。换句话说,该值不会作为属性公开。流行的序列化程序(如 Json.NET 或 System.Text.Json)默认只序列化属性。

如果您可以使用 JsonContent 而不是 StringContent,那么序列化将正常工作,因为它公开了 Value 作为属性。

var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = JsonContent.Create("Hello WORLD");
var responseInJson = JsonConvert.SerializeObject(response, Formatting.Indented);
responseInJson.Dump();

相关的 dotnet fiddle 链接:https://dotnetfiddle.net/NiM8lx

英文:

If you would use IActionResult as a return type of your method then you could take advantage of Ok and StatusCode methods of the base class. Your method could be rewritten like this:

[HttpGet]
public IActionResult MethodName()
{
    try
    {
        return Ok(&quot;Hello WORLD&quot;);
    }
    catch (Exception ex)
    {
        return StatusCode((int)HttpStatusCode.InternalServerError, &quot;{\&quot;error\&quot;: \&quot;&quot; + ex.Message + &quot;\&quot;}&quot;) ;
    }
}

Quite frankly I don't trully understand the sole purpose of your try-catch block but I hope you get the point.


UPDATE #1
> why I can't set HttpResponseMessage.Content correctly.

The StringContent does have a single property called Headers. In other words the value is not exposed as a property. The popular serializers (like Json.NET or System.Text.Json) serializes only the properties by default.

If you could use JsonContent instead of StringContent then the serialization will work correctly since it is exposing the Value as property.

var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = JsonContent.Create(&quot;Hello WORLD&quot;);	
var responseInJson = JsonConvert.SerializeObject(response, Formatting.Indented);
responseInJson.Dump();
{
   &quot;Version&quot;:&quot;1.1&quot;,
   &quot;Content&quot;:{
      &quot;ObjectType&quot;:&quot;System.String, System.Private.CoreLib, Version=7.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e&quot;,
      &quot;Value&quot;:&quot;Hello WORLD&quot;,
      &quot;Headers&quot;:[
         {
            &quot;Key&quot;:&quot;Content-Type&quot;,
            &quot;Value&quot;:[
               &quot;application/json; charset=utf-8&quot;
            ]
         }
      ]
   },
   &quot;StatusCode&quot;:200,
   &quot;ReasonPhrase&quot;:&quot;OK&quot;,
   &quot;Headers&quot;:[
      
   ],
   &quot;TrailingHeaders&quot;:[
      
   ],
   &quot;RequestMessage&quot;:null,
   &quot;IsSuccessStatusCode&quot;:true
}

Related dotnet fiddle link: https://dotnetfiddle.net/NiM8lx

huangapple
  • 本文由 发表于 2023年4月4日 08:32:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75924659.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定