您总是必须在 WebApi 中为您的控制器操作注册一个路由,这可以使用 attribute routing 或 conventions based routing 来完成。
在 GET 请求的查询字符串中传递的参数实际上不必在任一路由配置方法中明确指定。
您在控制器操作中指定的参数会映射到在 GET 请求的查询字符串中发送的参数。
如果您使用基于默认 WebApi 约定的设置,其中路由配置如下:
var config = new HttpConfiguration();
// some other config setup for web api
...
...
// route config
config.Routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
那么像这样的控制器会为你工作:
public class UsersController : ApiController {
// this maps to a get requests to:
// domain/api/users
// and domain/api/users?id=someid
// and domain/api/users?mail=somemail
// and domain/api/users?pw=somepw
// and domain/api/users?mail=somemail&pw=somepw
// and domain/api/users with any query string really
[HttpGet]
public IHttpActionResult Get(string mail, string pw) {
// should probably check mail and pw for empty strings and nulls
var users = SomeStaticExampleService.FindByMailAndPw(mail, pw);
return this.Json(users);
}
}
或者,您可以使用属性路由,然后调用您想要的任何控制器和操作方法。像这样配置你的路线:
var config = new HttpConfiguration();
// some other config setup for web api
...
...
// route config
config.MapHttpAttributeRoutes();
然后你可以像这样创建一个控制器:
public class FooController : ApiController {
// this maps to a get requests to:
// domain/users
// and domain/users?id=someid
// and domain/users?mail=somemail
// and domain/users?pw=somepw
// and domain/users with any query string really
[HttpGet]
[Route("users")]
public IHttpActionResult Bar(string mail, string pw) {
// should probably check mail and pw for empty strings and nulls
var users = SomeStaticExampleService.FindByMailAndPw(mail, pw);
return this.Json(users);
}
}
请记住,尽管使用 Attribute Routing 您必须小心不要创建冲突路由,否则 WebApi 将不知道将请求路由到哪个控制器和操作当一个路由映射到多个操作方法时。
我在这些示例中使用了this.Json 来返回一个带有 json 内容的 http 响应,以匹配您的 wcf ResponseFormat = WebMessageFormat.Json。但是你当然可以只返回一个 CLR 类型:
[HttpGet]
[Route("users")]
public IEnumerable<MyUser> Bar(string mail, string pw) {
// should probably check mail and pw for empty strings and nulls
var users = SomeStaticExampleService.FindByMailAndPw(mail, pw);
return users;
}
并让 WebApi 的 content negotiation 处理响应消息内容类型。