Asp.net-Mvc

為什麼無法導航到 web api 控制器

  • October 8, 2017

我第一次使用 Web API 將我的移動應用程序連接到 Web API。

我有 MVC 5 項目,我創建了 API 文件夾,並在裡面創建了ProductsController.

namespace DDD.WebUI.API
{
   public class ProductsController : ApiController
   {
       public string GetAllProducts()
       {
           return "Hello From WebAPI";
       }

   }
}

我曾嘗試從瀏覽器訪問此方法:

http://localhost:21879/DDD.WebUI/API/products/GetAllProducts

但我得到 404。

這可能很愚蠢,但無法弄清楚:(

更新

public static void RegisterRoutes(RouteCollection routes)
       {
           routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

           routes.MapRoute(
              name: "DefaultApi",
              url: "API/{controller}/{action}/{id}",
              defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
          );

           routes.MapRoute(
               name: "Default",
               url: "{controller}/{action}/{id}",
               defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
           );



       }

更新 2

我有一點進步:我有更新Application_Start()

GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);

WebApiConfig我有:

config.Routes.MapHttpRoute(
               name: "DefaultApi",
               routeTemplate: "api/{controller}/{id}",
               defaults: new { id = RouteParameter.Optional }
           );

我仍然將 API 控制器儲存在 Project/Api/ProductsController 但現在我可以訪問它但仍然無法從中獲得價值:

http://localhost:21879/api/products/getallproducts

但我得到的錯誤是:

<Error>
<Message>The request is invalid.</Message>
<MessageDetail>
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.String Get(Int32)' in 'GSL.WebUI.Api.ProductsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
</MessageDetail>
</Error>

我有同樣的問題。觀察您在 Global.asax.cs 中註冊路線的順序。

這有效:

GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);

這不會:

RouteConfig.RegisterRoutes(RouteTable.Routes);
GlobalConfiguration.Configure(WebApiConfig.Register);

如果你使用這種路由方式,你需要為動作指定允許的 Http 方法:

public class ProductsController : ApiController
{
   [HttpGet]
   public string GetAllProducts()
   {
       return "Hello From WebAPI";
   }
}

您可以從此連結獲取有關 API 路由的所有資訊:http ://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

引用自:https://stackoverflow.com/questions/25484176