【问题标题】:Return string from Web API .NET Core get operation从 Web API .NET Core 获取操作返回字符串
【发布时间】:2019-12-03 09:41:33
【问题描述】:

我有一个 get 操作,我想从中返回一个字符串。一个例子是

“000875”

当我从完全 .NET 的 Web API 控制器中的控制器返回此字符串时,它的格式如下:

{
  "Property": "000875"
}

当我在转换后的 .NET Core 控制器中返回字符串时,它会返回:

{
  "$id": "1",
  "$type": "System.Net.Http.HttpResponseMessage, System.Net.Http",
  "Version": "1.1",
  "Content": {
    "$id": "2",
    "$type": "System.Net.Http.StringContent, System.Net.Http",
    "Headers": [
      {
        "Key": "Content-Type",
        "Value": [
          "application/json; charset=utf-8"
        ]
      }
    ]
  },
  "StatusCode": "OK",
  "ReasonPhrase": "OK",
  "Headers": [],
  "TrailingHeaders": [],
  "RequestMessage": null,
  "IsSuccessStatusCode": true
}

有趣的是,该值甚至不在其中!

我正在运行一些有趣的 JSON 序列化来使 BreezeJs 与 .NET Core 一起工作。这可能是造成这种怪异的原因:

.AddNewtonsoftJson(opt =>
{
   // Let Breeze say how we serialize.  This adds in the Type and Id options the way breeze expects
   var jsonSerializerSettings = JsonSerializationFns.UpdateWithDefaults(opt.SerializerSettings);
   ......

我希望有一种方法可以在没有所有这些混乱的情况下让字符串通过。可以吗?

【问题讨论】:

  • 你能告诉我们包含返回行的API方法代码吗?

标签: asp.net-core breeze


【解决方案1】:

我的印象是主题操作定义返回HttpResponseMessage

public HttpResponseMessage MyAction(....

HttpRequestMessage 不再是 asp.net-core 框架中的一等公民,将被视为普通模型并被序列化。

这解释了您在控制器中看到的 JSON

语法需要更新以返回IActionResult派生响应

public IActionResult MyAction() {

    //...

    return Ok("000875");
}

ActionResult<T>

public ActionResult<string> MyAction() {

    //...
    if(somecondition)
        return NotFound();

    return "000875";
}

或模型本身。

public string MyAction() {

    //...

    return "000875";
}

参考Controller action return types in ASP.NET Core Web API

【讨论】:

    猜你喜欢
    • 2020-11-01
    • 1970-01-01
    • 2019-04-22
    • 1970-01-01
    • 2017-05-06
    • 2020-09-07
    • 2016-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多