ASP.NET 网络表单中的 ApiController 无法访问方法

ASP.NET ApiController inside a webform can't reach methods

无论如何,我无法从我的 Api 控制器访问任何方法,如果我尝试通过浏览器访问它,路由确实会出现,但没有显示任何方法。

我的控制器:

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;
        }
    }
}

我的全局 asax:

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

我在项目中有更多的网络表单(最初它只是 html 带有服务器端代码的页面,但我需要添加几个方法来检索和发送数据,非常感谢帮助!

EDIT1:我设法通过更改 URL 到达 HTTP 200,但无论如何我都无法访问这些方法(在调试模式下它不会在断点处停止)我如何才能正确路由 Api(所以它不是 Login.aspx)以及我如何修复达到的方法?

EDIT2:我在文档中读到我在全局中需要这一行:

RouteConfig.RegisterRoutes(RouteTable.Routes);

但是我没有使用 MVC 有关系吗?我尝试使用全新的 MVC Web Api 到达路线,它产生 "No Response"

在rest测试工具中添加的URL是

http://localhost:49342/api/get

方法类型为 GET

如果您从 aspx 页面调用此网站 api,请使用 httpClient class。

在您的控制器上使用路由器前缀。所以你访问 URL 作为

    http://localhost/routerprefix/router

HttpClient class 可用于发送和接收 HTTP 请求和响应。由于您正尝试从 aspx 页面使用 WebApi,更好的方法是创建一个 HttpClient 实例

下面是一个非常简单的实现。请检查此 url 以获取更多信息

MSDN sample


    HttpClient client = new HttpClient();

    HttpResponseMessage response = await client.GetAsync("http://localhost:49342/api/get");
    if (response.IsSuccessStatusCode)
    {
        product = await response.Content.ReadAsAsync();
    }

从你的设置来看,似乎是正确的

你有:

  1. config.MapHttpAttributeRoutes(); - 设置属性路由
  2. config.Routes.MapHttpRoute( - 设置默认路由
  3. GlobalConfiguration.Configure(WebApiConfig.Register); - 在启动时注册

所以它应该可以工作。

我认为您遇到的问题是您调用它的方式

WebAPI 路由的工作方式与 MVC 略有不同

例如:

在你get方法中,路由设置如下

[HttpGet, Route("api/get")]

因此您应该使用 GET http 方法{host}/api/get 调用它

在屏幕截图中,您正在使用 {host}/api/get/Get 进行呼叫 - 这不会起作用,因为没有路由会匹配

与您的 POST 方法相同

所以再试一次,你应该能达到它