要使用Casablanca/cpprestsdk支持HTTP方法,您可以使用这样的代码
http_listener listener(U("http://localhost:10000/restdemo"));
listener.support(methods::GET, handle_get);
listener.support(methods::POST, handle_post);
listener.support(methods::PUT, handle_put);
listener.support(methods::DEL, handle_del);
当handle_get、handle_post等只是函数时,这工作正常。但是一旦我尝试在控制器类中实现它,handle_get、handle_post等都是方法,我就会收到如下错误:
error: no matching function for call to ‘Controller::handle_get()’
error: invalid use of non-static member function ‘void Controller::handle_get(web::http::http_request)
我在文档中没有看到任何关于方法不起作用的原因。我也仔细阅读了这些问题,没有看到任何与我的问题相关的内容。
有什么明显的原因为什么听众支持会努力找到方法吗?
我认为您需要绑定方法
listener.support(methods::GET, std::bind(&Controller::handle_get, this, std::placeholders::_1));
http_listener::support
接受类型为const std::function< void(http_request)> &handler
的参数,这意味着您可以传递任何 Callable 类型,因此,为了使用成员函数,您可以使用以下内容:
listener.support(methods::GET, [this](web::http::http_request http_request)
{
// call your member function here or handle your request here
});
或
listener.support(methods::GET, std::bind(&MyClass::my_handler, this, std::placeholders::_1));
第一个示例使用捕获this
的 lambda,第二个示例通过函数创建调用包装器MyClasss::my_handler