无论如何我无法从我的ApiController到达任何方法,如果我尝试通过浏览器访问它但没有显示任何方法,则会出现路由。
我的控制器:
namespace AgroRiego.Controllers
{
public class datacontrol : ApiController
{
[HttpGet, Route("api/get")]
public string Get([FromUri]string user, string pass)
{
string check = SQL.Reader("SELECT * FROM users WHERE username='" + user + "' AND password='" + pass + "'");
if (String.IsNullOrWhiteSpace(check))
{
return "error en credenciales";
}
DataTable horarios = SQL.table_read("SELECT * FROM horario_riego");
string json = Utils.ConvertDataTabletoJSON(horarios);
return json;
}
[HttpPost, Route("api/post")]
public void Post([FromBody]string value)
{
string i = value;
}
}
}
我的全球性问题:
namespace AgroRiego
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
}
和我的webapiconfig:
namespace AgroRiego
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Configuración y servicios de API web
// Rutas de API web
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
我在项目中有更多的webforms(原来它只是带有服务器端代码的html页面,但我需要添加一些方法来检索和发送数据,非常感谢!
EDIT1:我设法达到HTTP 200更改URL但我无法到达方法(在调试模式下它不会在断点上停止)如何正确路由Api(所以它不是Login.aspx)以及如何我修复了达到的方法吗?
EDIT2:我在文档中读到我在全球范围内需要这一行:
RouteConfig.RegisterRoutes(RouteTable.Routes);
但是我没有使用MVC那么重要吗?我尝试使用全新的MVC Web Api到达路线并产生“无响应”
在控制器上使用routerprefix。所以你访问URL作为
http://localhost/routerprefix/router
HttpClient类可用于发送和接收HTTP请求和响应。由于您尝试从aspx页面使用WebApi,因此更好的方法是创建HttpClient实例
下面是一个非常简单的实现。请查看此网址以获取更多信息
HttpClient client = new HttpClient(); HttpResponseMessage response = await client.GetAsync("http://localhost:49342/api/get"); if (response.IsSuccessStatusCode) { product = await response.Content.ReadAsAsync(); }
从您的设置看,它似乎是正确的
你必须:
config.MapHttpAttributeRoutes();
- 设置属性路由config.Routes.MapHttpRoute(
- 设置默认路线GlobalConfiguration.Configure(WebApiConfig.Register);
- 在初创公司注册所以它应该工作。
我认为你遇到的问题就是你打电话的方式
Web API路由与MVC略有不同
例如:
在get get方法中,路由设置如下
[HttpGet, Route("api/get")]
所以你应该使用GET http方法将其命名为{host}/api/get
在屏幕截图中,你正在使用{host}/api/get/Get
调用 - 这将无法工作,因为没有路由匹配
对于您的POST方法也是如此
所以再试一次,你应该能够达到它
要在其余测试工具中添加的URL是
http://localhost:49342/api/get
方法类型是GET
如果从aspx页面调用此web api,请使用httpClient类。