控制器可以支持带有可变字符串参数的路由吗? [英] Can a Controller support a route with variable string parameters?

查看:24
本文介绍了控制器可以支持带有可变字符串参数的路由吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想支持/route/param1/route/param1/param2/route/param1/param2/param3等路由> 等等.

I want to support routes such as /route/param1, /route/param1/param2, /route/param1/param2/param3 and so on.

现在我已经在我的控制器中为每个参数组合定义了一个路由:

For now I have define in my Controller one route per combination of parameters:

    [Route("{path1}")]
    public async Task<IActionResult> Route1(string path1)
    {
        return await ParsePath(new[] { path1 });
    }

    [Route("{path1}/{path2}")]
    public async Task<IActionResult> Route2(string path1, string path2)
    {
        return await ParsePath(new[] { path1, path2 });
    }

这有两个主要缺点:

  • 目前我有 8 个,所以我最多只能支持 8 个参数
  • 如果我想支持更多参数,这段代码不是很干

我更喜欢使用具有这样签名的方法:

I would prefer to use a method with such signature:

    public async Task<IActionResult> RouteMultiple(params string[] paths)
    {
        return await ParsePath(queryString, paths);
    }

但这与 Route 属性兼容吗?

but is this compatible with the Route attribute?

推荐答案

关于这个:

  [Route("{path1?}/{path2?}/{path3?}/{path4?}")]
public async Task<IActionResult> RouteMultiple(string path1, string path2, ... and so on)
    {
        return await ParsePath(new[] { path1, path2, ... and so on });
    }

它适用于 Postman.

It works in Postman.

这篇关于控制器可以支持带有可变字符串参数的路由吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆