如何在ASP.NET Core中绑定JSON主体中的多个原始值

qqrboqgw  于 5个月前  发布在  .NET
关注(0)|答案(1)|浏览(75)

此问题在此处已有答案

Binding .NET Core Json to simple parameters(2个答案)
26天前关闭。
一个旧的大型ASP.NETMVC5遗留应用程序使用以下方法绑定JSON主体中的多个原始值。
JSON body示例:

{
    "text": "foo",
    "value": 42
}

字符串
示例操作:

public class FooController : System.Web.Mvc.Controller
{
  public async Task<IHttpActionResult> GetAsync(string text, int value)
  {
      // ...
  }
}


当控制器从Microsoft.AspNetCore.Mvc.ControllerBase继承时,如何在ASP.NET Core中实现相同的功能,同时对现有代码进行最小的更改?

g9icjywg

g9icjywg1#

最简单的方法,在我看来-创建一个类/模型来将请求主体抽象为:

public class TextValuePair
{
    public string Text { get; set; }

    public int Value { get; set; }
}

字符串
然后(noting that GET request bodies are supposed to have no semantic meaning...),你的动作签名如下:

[HttpPost]
  public async Task<IActionResult> RenameMeAsync([FromBody] TextValuePair tvp)
  {
      // ...
  }

相关问题