在 .net core Restful API 中如何更改 URL 格式以获取具有单个方法名称的双参数?

In .net core Restful API how to change URL format to get double parameter with single method name?

使用 URL 的这两种格式,这些代码可以正常工作:

http://localhost:51996/weatherforecast/help/p1
http://localhost:51996/weatherforecast/help/p1/p2

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    [HttpGet("help/{a}")]
    [Route("help")]
   
    public string help( string  a)
    {
        return "single param";
    }

    [HttpGet("help/{b}/{c}")]
    [Route("help")]
    public string help( string b,string c)
    {
        return "double param";
    }
}

但是我怎样才能改变我的路线或任何东西来处理这种类型的 URL:

http://localhost:51996/weatherforecast/help?a=p1
http://localhost:51996/weatherforecast/help?b=p1&c=p2

您正在从查询字符串中提取。所以你的路线设置错误。试试这个:

[HttpGet, Route("help")]
public string help([FromQuery] string  a)
{
    return "single param";
}

[HttpGet, Route("help")]
public string help([FromQuery]string b, [FromQuery] string c)
{
    return "double param";
}

但是,这里的问题是您必须使用相同的路线。默认查询字符串是 可选的 。所以这两个可以用同样的方式调用,框架不知道调用哪个。

示例:您可以调用 https://example.com/api/Controller/help,这两种方法都是该请求可接受的端点。

所以你需要一种方法来区分这两者。

要么更改端点的名称:

[HttpGet, Route("helpA")]
public string helpA([FromQuery] string  a)
{
    return "single param";
}

[HttpGet, Route("helpBC")]
public string helpBC([FromQuery]string b, [FromQuery] string c)
{
    return "double param";
}

// https://www.example.com/api/Controller/helpA/?a=string
// https://www.example.com/api/Controller/helpBC/?b=string1&c=string2

或者,您可以更改路径并使字符串成为必需的:

[HttpGet, Route("help/{a}")]

public string helpA(string  a)
{
    return "single param";
}

[HttpGet, Route("help/{b}/{c}")]
public string helpBC(string b, string c)
{
    return "double param";
}

// https://www.example.com/api/Controller/help/string
// https://www.example.com/api/Controller/help/string1/string2

您可以做的另一件事是将所有这三种方法结合起来,然后确保您的文档解释了它们应该使用其中一种:

[HttpGet, Route("help")]
public string helpABC(
    [FromQuery]string a, [FromQuery]string b, [FromQuery]string c)
{
    if(string.IsNullOrEmpty(a)){
        // b and c must not be null or empty
    }
    // etc...
}