且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在ASP.NET Core的URL查询中使用破折号

更新时间:2022-01-07 05:15:22

路由参数通常直接映射到操作的变量名称,因此[Route("customers/{customerId}/orders")]应该起作用,因为那是变量的名称( int customerId).

The route parameters usually directly map to the action's variable name, so [Route("customers/{customerId}/orders")] should work since that's the name of your variable (int customerId).

不需要在此处短划线,花括号{}中的部分将永远不会显示为生成的url的一部分,它将始终被您从浏览器传递的内容替换或您传递给网址生成器的变量.

You don't need dashes there, the part within the curly braces {} will never appear as a part of the generated url, it will always be replaced by the content you pass from browser or the variables you pass to the url generator.

customers/{customerId}/orders将始终为customers/1/orders,因此没有必要尝试将其强制为{customer-id}.

customers/{customerId}/orders will always be customers/1/orders when customerId is set to 1, so there's no point trying to force it to {customer-id}.

但是,您可以尝试公开

[Route("customers/{customer-id}/orders")]
IActionResult GetCustomerOrders([FromRoute(Name = "customer-id")]int customerId, bool activeOrders)

如果需要,可以使用

绑定来自非常规路线名称的customerId.但我强烈建议您这样做,因为它只会添加不必要的代码,这些代码对您生成的网址绝对为零效果.

to bind the customerId from a unconventional route name, if you wish. But I'd strongly advise against it, as it just adds unnecessary code which has absolutely zero-effect on your generated urls.

上面的代码生成(并解析)与

The above generates (and parses) the exactly same url as

[Route("customers/{customerId}/orders")]
IActionResult GetCustomerOrders(int customerId, bool activeOrders)

并且是更具可读性的代码.

and is much more readable code.

对于查询部分,正如您在注释中指出的那样,通过[FromQuery(Name = "active-orders")] bool activeOrders添加破折号是有意义的,因为这确实会影响生成的url.

For the query part, as you figured it out in the comments, it makes sense to add the dashes via [FromQuery(Name = "active-orders")] bool activeOrders, since that really affects the generated url.

在ASP.NET Core 2.2中,您将获得一个新选项来段塞"您的路由(仅在使用新的Route Dispatcher而不是默认的Mvc路由器时才受支持).

In ASP.NET Core 2.2 you'll get a new option to 'slugify' your routes (only supported when using the new Route Dispatcher instead of the default Mvc Router).

blog\{article:slugify} 的路由(与Url.Action(new { article = "MyTestArticle" })一起使用时)将生成blog\my-test-article作为网址.

A route of blog\{article:slugify} will (when used with Url.Action(new { article = "MyTestArticle" })) generate blog\my-test-article as url.

也可以在默认路由中使用:

Can also be used in default routes:

routes.MapRoute(
    name: "default",
    template: "{controller=Home:slugify}/{action=Index:slugify}/{id?}");

有关更多详细信息,请参见

For further details see the ASP.NET Core 2.2-preview 3 annoucement.