使用 Get 请求的 WebApi2 路由不起作用

WebApi2 Routing with Get Request does not work

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

我希望能够使用

搜索我的用户

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

但这不起作用。我收到一个错误:

{ "Message": "No HTTP resource was found that matches the request URI 'http://localhost:63881/api/user/search'.", "MessageDetail": "No action was found on the controller 'User' that matches the request." }

我有这样的代码

[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");
    }

谢谢!

向 SearchGet 方法添加另一个路由属性应该可行:

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

它会根据querystring参数的个数和名称或者每个querystring参数来映射请求。