Toh*_*hid 2 asp.net-core-mvc asp.net-core asp.net-core-2.1
我们可以Route在ASP.NET Core 的模板中使用破折号(-)吗?
// GET: api/customers/5/orders?active-orders=true
[Route("customers/{customer-id}/orders")]
public IActionResult GetCustomerOrders(int customerId, bool activeOrders)
{
.
.
.
}
Run Code Online (Sandbox Code Playgroud)
(以上代码无效)
路线参数通常直接映射到操作的变量名,因此[Route("customers/{customerId}/orders")]应该起作用,因为那是变量的名称(int customerId)。
您无需在此处使用破折号,花括号中的部分{}将永远不会显示为生成的url的一部分,它将始终被您从浏览器传递的内容或传递给url生成器的变量替换。
customers/{customerId}/orders始终将customers/1/orderswhen customerId设置为1,因此没有必要尝试将其强制为{customer-id}。
但是,您可以尝试公开
[Route("customers/{customer-id}/orders")]
IActionResult GetCustomerOrders([FromRoute(Name = "customer-id")]int customerId, bool activeOrders)
Run Code Online (Sandbox Code Playgroud)
customerId如果需要,可以从非常规路线名称绑定。但我强烈建议您这样做,因为它只会添加不必要的代码,这些代码对您生成的网址绝对是零影响。
上面的代码生成(并解析)与以下网址完全相同的网址
[Route("customers/{customerId}/orders")]
IActionResult GetCustomerOrders(int customerId, bool activeOrders)
Run Code Online (Sandbox Code Playgroud)
并且是更具可读性的代码。
对于查询部分,正如您在注释中指出的那样,通过来添加破折号是有意义的[FromQuery(Name = "active-orders")] bool activeOrders,因为这确实会影响所生成的url。
在ASP.NET Core 2.2中,您将获得一个新选项来“散布”您的路由(仅在使用新的Route Dispatcher而不是默认的Mvc Router时才受支持)。
blog\{article:slugify}will 路由(与结合使用时Url.Action(new { article = "MyTestArticle" }))会生blog\my-test-article成为url。
也可以在默认路由中使用:
routes.MapRoute(
name: "default",
template: "{controller=Home:slugify}/{action=Index:slugify}/{id?}");
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请参见ASP.NET Core 2.2预览版3。
| 归档时间: |
|
| 查看次数: |
888 次 |
| 最近记录: |