【发布时间】:2014-10-18 12:01:45
【问题描述】:
我第一次使用 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>
【问题讨论】:
-
回答您的更新。如果您以这种方式定义映射,则不应在 url 中使用该操作。试试
http://localhost:21879/api/products/,它应该可以工作。然后查看我的答案中的链接以了解一切如何协同工作。
标签: asp.net-mvc asp.net-web-api asp.net-web-api2 asp.net-web-api-routing