简体   繁体   中英

Routing optional parameters

I'm working on my first web api and I'm stuck trying to create rules for these urls

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

My current routing rules are

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

And my methods serving these urls

// 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";
}

I have 2 problems

1) http://mydomain.com/values/ is not resolving

2) http://mydomain.com/values/?param1=test1 and http://mydomain.com/values/?param2=test2 are not resolving.

Could you help me to create routes for serving these urls?

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

Should do what you need. Query string parameters are already mapped to Action parameters as long as they are named the same, no need to add them in the route.

First you don't need the route

routes.MapHttpRoute(
  name: "Route2",
  routeTemplate: "{controller}/{param1}/{param2}",
  defaults: new { param1 = RouteParameter.Optional, param2 = RouteParameter.Optional }
);

Secondly to resolve http://mydomain.com/values/ you need to make parameter id optional by making it int?

// GET values/5
public string Get(int? id)
{
  return "value";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM