我如何在属性中使用查询参数?

问题描述 投票:1回答:1

我想在端点属性中使用查询参数,但不确定如何使用它们。

我尝试过:

[HttpPost("fooBar/{version}?amount={amount}&date={date}")]

但我却收到此错误:

Microsoft.AspNetCore.Routing.Patterns.RoutePatternException:文字部分'?amount ='无效。文字部分不能包含“?”字符。在Microsoft.AspNetCore.Routing.Patterns.RoutePatternParser.Parse(字符串模式)

或者,如果我想击中一个上面的端点,什么是设置查询参数的正确方法?

c# asp.net-core query-parameters mediatr asp.net-core-routing
1个回答
3
投票

不要在路由模板中使用它们,一旦操作中有匹配的参数,它们就会被包括在内。

//POST fooBar/v2?amount=1234&date=2020-01-06
[HttpPost("fooBar/{version}")]
public IActionResult FooBar(string version, int amount,  DateTime date) {
    //...
}

或使用属性明确说明它们的来源

//POST fooBar/v2?amount=1234&date=2020-01-06
[HttpPost("fooBar/{version}")]
public IActionResult FooBar([FromRoute]string version, [FromQuery]int amount,  [FromQuery]DateTime date) {
    //...
}

参考Model Binding in ASP.NET Core

© www.soinside.com 2019 - 2024. All rights reserved.