通过查询参数

时间:2015-08-01 08:41:14

标签: asp.net asp.net-web-api asp.net-web-api2

我要从我的WCF Rest / Json服务切换到WebApi2,我正在寻找一种方法来映射这种方法:

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

我想通过电子邮件和密码查询用户,因此我无法使用打算使用ID的默认GET。据我所知,你应该通过Rest ...中的属性来做到这一点。

我是否只需为此注册一条路线,或者是否有更好的方法(可能按惯例)?

1 个答案:

答案 0 :(得分:15)

您必须在 WebApi 中为控制器操作注册路线,这可以通过attribute routingconventions 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);
   }
}

请记住,使用属性路由时,必须注意不要创建冲突路由,否则 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处理响应消息内容类型。

相关问题