【发布时间】:2021-12-01 21:09:50
【问题描述】:
我刚开始学习 asp.net MVC6 并尝试了解其中的工作原理。目前,我正在使用.net 5.0。 所以这是 WebAPI 方法,我只是向它添加了一个对象参数 weatherForecast:
[BindProperties(SupportsGet = true)]
public class WeatherForecast
{
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string Summary { get; set; }
}
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
[HttpGet]
public IEnumerable<WeatherForecast> Get(WeatherForecast weatherForecast)
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
当我从浏览器甚至邮递员向此方法发送 GET 请求时:
http://localhost:1382/WeatherForecast?TemperatureC=12&Summary=HelloWorld
返回:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.13",
"title": "Unsupported Media Type",
"status": 415,
"traceId": "00-a556c5fbdce0748bf3c7bd0e3200e92-21f4bf6470b534d-00"
}
有趣的是,如果我在 PostMan 中添加一个带有 GET 请求的 JSON 正文(仅用于测试),那么它可以正常工作而不会出现任何错误。 我阅读了 Microsoft 模型绑定文档 [这里是链接][1],它说: “默认情况下,属性不绑定到 HTTP GET 请求” 所以我们必须使用属性 [BindProperty(SupportsGet = true)] 或 [BindProperties(SupportsGet = true)] 并且即使在使用这个属性之后它仍然不起作用.
所以在深入挖掘之后,我发现了一个属性 [FromQuery] 并在将其与对象参数 weatherForecast 一起使用后,它开始工作。但是我想知道为什么没有这个属性就不行?
通常在 MVC5 中,如果我们不使用 [FromUri] 等参数指定任何属性,则模型绑定器会自动绑定在查询字符串中发送的参数。
我在这里缺少什么? [1]:https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-5.0#targets
【问题讨论】:
-
没有“.NET Framework 5.0”之类的东西——“.NET 5”不是 .NET Framework 4.x 的直接继承者(和“ASP.NET MVC 5”与 ASP.NET for .NET 5 无关。
-
WeatherForecast的定义是什么? -
我怀疑你不明白 HTTP
GET请求和查询字符串参数是如何工作的...... -
@Dai 我已经编辑了我的问题并添加了 WeatherForecast 的定义。
-
试试
public IEnumerable<WeatherForecast> Get([FromQuery] int TemperatureC, [FromQuery] string summary)stackoverflow.com/questions/49741284/…。您的函数需要来自 Type: WeatherForecast 的对象,但是您通过 http get 传递的是两个参数作为 http 查询。阿法克
标签: c# asp.net-core asp.net-web-api asp.net5