问题描述
使用这两种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...
}