在ASP.NET Core

时间:2018-10-27 14:34:55

标签: asp.net-core asp.net-core-mvc asp.net-core-2.1

我们可以在ASP.NET Core的Route模板中使用破折号(-)吗?

// GET: api/customers/5/orders?active-orders=true
[Route("customers/{customer-id}/orders")]
public IActionResult GetCustomerOrders(int customerId, bool activeOrders)
{
    .
    .
    .
}

(以上代码无效)

2 个答案:

答案 0 :(得分:3)

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

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

customers/{customerId}/orders设置为1时,

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

但是,您可以尝试公开

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

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

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

完全相同的 网址

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

,并且代码更具可读性。

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

ASP.NET Core 2.2的新功能

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

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

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

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

有关更多详细信息,请参见ASP.NET Core 2.2-preview 3 annoucement

答案 1 :(得分:1)

只需在 Tseng 答案上进行扩展即可。为了使ASP NET CORE使用“ slugify” 转换器,您需要先注册它,如下所示:

public class SlugifyParameterTransformer : IOutboundParameterTransformer
{
    public string TransformOutbound(object value)
    {
        if (value == null) { return null; }

        return Regex.Replace(value.ToString(), 
                             "([a-z])([A-Z])",
                             "$1-$2",
                             RegexOptions.CultureInvariant,
                             TimeSpan.FromMilliseconds(100)).ToLowerInvariant();
    }
}

,然后在Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();

    services.AddRouting(options =>
    {
        options.ConstraintMap["slugify"] = typeof(SlugifyParameterTransformer);
    });
}

Code from Microsoft

相关问题