Web API 2 通过查询参数获取

Web API 2 GET by query parameter

我打算从我的 WCF Rest/Json 服务切换到 WebApi2,我正在寻找映射此方法的方法:

[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "Users?mail={mail}&pw={pw}")]
UserData getUserByEmailAndPw(String mail);

我想通过电子邮件和密码查询用户,因此无法使用旨在使用 ID 的默认 GET。据我所知,您应该通过 Rest 中的属性来执行此操作...

我是否只需要为此注册一条路线,还是有更好的方法(也许按照惯例)?

您总是需要在 WebApi 中为您的控制器操作注册一个路由,这可以通过 attribute routing or with 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 来 return 具有 json 内容的 http 响应以匹配您的 wcf ResponseFormat = WebMessageFormat.Json.但是你当然可以 return a CLR type:

   [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 处理响应消息内容类型。