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

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

问题描述

我想支持诸如/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 属性兼容吗?

推荐答案

这是怎么回事:

  [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 });
    }

它可以在邮递员中使用.

It works in Postman.

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

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