路由可选参数

Sta*_*wer 2 c# asp.net asp.net-web-api

我正在研究我的第一个web api,我一直试图为这些网址创建规则

1) http://mydomain.com/values/4 --> this number can be any, this is just an example
2) http://mydomain.com/values/
3) http://mydomain.com/values/?param1=test1&param2=test2
4) http://mydomain.com/values/?param1=test1
5) http://mydomain.com/values/?param2=test2
Run Code Online (Sandbox Code Playgroud)

我目前的路由规则是

routes.MapHttpRoute(
    name: "Route1",
    routeTemplate: "{controller}/{id}/"
);
routes.MapHttpRoute(
    name: "Route2",
    routeTemplate: "{controller}/{param1}/{param2}",
    defaults: new { param1 = RouteParameter.Optional, param2 = RouteParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)

我的方法服务于这些网址

// GET values/
// GET values/?param1=test1&param2=test2
// GET values/?param1=test1
// GET values/?param2=test2
public IEnumerable Get(string param1, string param2)
{
    return new string[] { "value1", "value2" };
}

// GET values/5
public string Get(int id)
{
    return "value";
}
Run Code Online (Sandbox Code Playgroud)

我有2个问题

1)http://mydomain.com/values/没有解决

2)http://mydomain.com/values/?param1=test1http://mydomain.com/values/?param2=test2没有解决.

你能帮我创建服务这些网址的路线吗?

Mae*_*ess 5

routes.MapHttpRoute(
    name: "Route1",
    routeTemplate: "{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)

应该做你需要的.查询字符串参数已经映射到Action参数,只要它们的名称相同,不需要在路由中添加它们.