我第一次使用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>
我想看着你更新你的行动,需要id
哪些是不可为空int
和你没有提供它只是修改URL作为http://localhost:21879/API/products/GetAllProducts/2
这里'2'
被分配到'id'
,它会工作。
在WebApiConfig中,将路由修改为:
config.Routes. MapHttpRoute (
name: "DefaultApi" ,
routeTemplate: "api/{controller}/{action}/{id}" ,
defaults: new { id = RouteParameter . Optional }
);
只需更改此Mvc路线:
routes. MapRoute(
name: "DefaultApi" ,
url: "API/{controller}/{action}/{id}" ,
defaults: new { controller = "Home" , action = "Index" , id = UrlParameter .Option
);
有了这个 :
routes. MapRoute(
name: "DefaultApiMvc" ,
url: "APIMvc/{controller}/{action}/{id}" ,
defaults: new { controller = "Home" , action = "Index" , id = UrlParameter .Option
);
因为否则Mvc和Api路由会相互冲突...
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句