我将从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中为控制器操作注册路由,这可以通过属性路由或基于约定的路由来完成。
实际上,不必在任一路由配置方法中显式指定在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的 内容协商处理响应消息的内容类型。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句