从Web API.NET核心获取操作返回字符串 [英] Return string from Web API .NET Core get operation

查看:9
本文介绍了从Web API.NET核心获取操作返回字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个GET操作,我想从该操作返回一个字符串。例如

"000875"

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

{
  "Property": "000875"
}

当我在转换后的.NET核心控制器中返回该字符串时,它返回以下内容:

{
  "$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);
   ......

我希望有一种方法可以让字符串通过而不会弄得一团糟。这能做到吗?

推荐答案

我感觉主题操作定义返回HttpResponseMessage

public HttpResponseMessage MyAction(....

HttpRequestMessage不再是ASP.NET核心框架中的一等公民,将被视为普通模型并序列化。

这解释了您在控制器上看到的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

这篇关于从Web API.NET核心获取操作返回字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆