首页 > 解决方案 > 有没有办法将 HttpGet 方法的参数组合成一个对象?

问题描述

我的控制器中有以下方法。

[HttpGet]
public ActionResult MyGetMethod(string address, string zip, int width) {...}

它被称为通过http://foo.com/home/MyGetMethod?address=234MainSt&zip=90210&width=123

有没有办法将参数地址,zip和宽度组合成一个对象,并以以下方式将对象传递给方法?

[HttpGet]
public ActionResult MyGetMethod(Foo myParam) {...}

public class Foo {
   public string Address {get; set;}
   public string Zip {get; set;}
   public int Width {get; set;}
}

对于旧的 ASP.NET MVC,有一个模糊相关的问题,似乎表明这对于该技术来说是不可能的。

.NET Core 2.x 可以吗?

标签: c#.net.net-coreasp.net-core-mvc

解决方案


您在 queryString 中的数据,因此您需要提供者 [FromQuery]

[来自查询]

[HttpGet]
public ActionResult MyGetMethod([FromQuery]Foo myParam) {...}

public class Foo {
   public string Address {get; set;}
   public string Zip {get; set;}
   public int Width {get; set;}
}

推荐阅读