带有Get Request的WebApi2路由不起作用

时间:2015-11-12 23:09:22

标签: asp.net-web-api2

您好我正在创建一个简单的程序,您可以搜索用户,注册用户,并获取所有已注册的用户。

我希望能够使用

搜索我的用户
  

/ api / user / search?name = ...& email = B

但这不起作用。我收到的错误是:

  

{     “消息”:“找不到与请求URI'http://localhost:63881/api/user/search'匹配的HTTP资源。”,     “MessageDetail”:“在控制器'User'上找不到与请求匹配的操作。”   }

我的代码看起来像这样

[RoutePrefix("api/user")]
public class UserController : ApiController
{
    public HttpResponseMessage Get() {
        // Check if the user is in the database 
        return Request.CreateResponse(HttpStatusCode.OK, "Return All");
    }

    public HttpResponseMessage Post(UserForm form) {
        if (ModelState.IsValid == false) {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
        }
        if (form == null) {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Please enter data");
        }
        // Register the person
        return Request.CreateResponse(HttpStatusCode.OK, "Register");
    }

    [Route("search/{name}/{email}")]
    [HttpGet]
    public HttpResponseMessage SearchGet(string name, string email) {
        return Request.CreateResponse(HttpStatusCode.OK, "Found");
    }

谢谢!

1 个答案:

答案 0 :(得分:0)

为SearchGet方法添加另一个路由属性应该有效:

[Route("search") ] 
[Route("search/{name}/{email}")]
    [HttpGet]
    public HttpResponseMessage SearchGet(string name, string email) {
        return Request.CreateResponse(HttpStatusCode.OK, "Found");
    }

它将根据查询字符串参数count和name或每个querystring参数映射请求。