Skip to main content
 首页 » 编程设计

c#之REST API 可选参数

2024年02月06日12tuyile006

我用 rest api 构建了一个 Web 角色。它的所有参数都应该是可选的,具有默认值

我试过这个:

  [WebGet(UriTemplate = "RetrieveInformation/param1/{param1}/param2/{param2}/param3/{param3}")] 
    public string RetrieveInformation(string param1, string param2, string param3) 
    { 
 
    } 

我希望它适用于以下场景:

https://127.0.0.1/RetrieveInformation/param1/2   
 
https://127.0.0.1/RetrieveInformation/param1/2/param3/3  

我该怎么做?下面的方法行得通吗?

[WebGet(UriTemplate = "RetrieveInformation/param1/{param1=1}/param2/{param2=2}/param3/{param3=3}")] 

请您参考如下方法:

我认为使用段(即使用/)无法实现此目的。您可以使用通配符,但它只允许您对最后一段这样做。

[WebGet(UriTemplate = "RetrieveInformation/param1/{param1}/{*param2}")] 

如果你真的不需要分段并且可以使用查询参数,下面的路由就可以了

[WebGet(UriTemplate = "RetrieveInformation?param1={param1}&param2={param2}&param3={param3}")] 

这样的路线会给你带来灵 active ,因为参数不需要排序,也不是必需的。这将适用于以下内容

http://localhost:62386/Service1.svc/GetData?param1=1&param2=2&param3=3 
http://localhost:62386/Service1.svc/GetData?param1=1&param3=3&param2=2 
http://localhost:62386/Service1.svc/GetData?param1=1&param2=2 
http://localhost:62386/Service1.svc/GetData?param1=1&param3=3 

您可以找到有关 UriTemplate @ http://msdn.microsoft.com/en-us/library/bb675245.aspx 的更多信息

希望对你有帮助