简体   繁体   English

路由可选参数

[英]Routing optional parameters

I'm working on my first web api and I'm stuck trying to create rules for these urls 我正在使用我的第一个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

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 我有2个问题

1) http://mydomain.com/values/ is not resolving 1) http://mydomain.com/values/无法解析

2) http://mydomain.com/values/?param1=test1 and http://mydomain.com/values/?param2=test2 are not resolving. 2)无法解析http://mydomain.com/values/?param1=test1http://mydomain.com/values/?param2=test2

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. 只要查询字符串参数的名称相同,它们就已经映射到Action参数,而无需在路由中添加它们。

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? 其次,要解析http://mydomain.com/values/您需要通过将其设置为int?来使参数id可选int?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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